From 301b0ccf7acc647505797534083a04b53df4d3b5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=BE=D0=BB=D0=B0=D0=B9=20=D0=91=D0=B5?= =?UTF-8?q?=D0=BB=D0=BE=D0=BD=D0=BE=D0=B3=D0=BE=D0=B2?= Date: Mon, 30 Nov 2026 14:47:12 +0300 Subject: [PATCH 1/2] feat(pool): add PoolEntryStateMachine A one-shot state machine, PoolEntryStateMachine, has been added to manage the lifecycle of a PoolEntry. --- .../io/tarantool/pool/entry/ClosedState.java | 81 +++++++ .../io/tarantool/pool/entry/ClosingState.java | 94 ++++++++ .../tarantool/pool/entry/ConnectingState.java | 97 ++++++++ .../pool/entry/ConnectionMetrics.java | 41 ++++ .../pool/entry/ConnectionSession.java | 99 ++++++++ .../io/tarantool/pool/entry/EntryEvent.java | 13 +- .../io/tarantool/pool/entry/EntryState.java | 145 ++++++++++++ .../io/tarantool/pool/entry/InitState.java | 42 ++++ .../pool/entry/PolicyRestartingState.java | 40 ++++ .../pool/entry/PolicyStartingState.java | 58 +++++ .../pool/entry/PolicyStoppingState.java | 101 ++++++++ .../pool/entry/PoolEntryStateMachine.java | 221 ++++++++++++++++++ .../io/tarantool/pool/entry/RunningState.java | 29 +++ .../schemas/pool-entry/PoolEntry.puml | 43 ++++ 14 files changed, 1099 insertions(+), 5 deletions(-) create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/ClosedState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/ClosingState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectingState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectionMetrics.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectionSession.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/EntryState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/InitState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyRestartingState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyStartingState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyStoppingState.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/PoolEntryStateMachine.java create mode 100644 tarantool-pooling/src/main/java/io/tarantool/pool/entry/RunningState.java create mode 100644 tarantool-pooling/src/main/resources/schemas/pool-entry/PoolEntry.puml diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ClosedState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ClosedState.java new file mode 100644 index 00000000..e77e1746 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ClosedState.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import io.tarantool.pool.availability.Metadata; +import io.tarantool.pool.entry.EntryEvent.ClientCloseEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectEvent; +import io.tarantool.pool.entry.EntryEvent.ReconnectEvent; +import io.tarantool.pool.entry.EntryEvent.RemoteCloseEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; +import io.tarantool.pool.exceptions.PoolClosedException; + +/** + * The terminal state. The machine is never reused: the pool entry creates a new one when it needs + * to reconnect. + * + *

On entry the state emits {@code onConnectionClosed}, completes the connect and close futures + * and calls the finish callback with the outcome of the session. Nothing that fails there may + * prevent the later steps: the pool entry relies on the callback to reconnect. + */ +final class ClosedState extends EntryState { + + ClosedState(PoolEntryStateMachine machine) { + super(machine, "CLOSED"); + } + + @Override + void enter() { + final Outcome outcome = ctx().outcome; + // The finish callback and the futures must be reached whatever fails here: the entry relies on + // the callback to reconnect. The listener notification is guarded on its own. + try { + final Metadata meta = this.machine.view().metadata(); + this.machine.view().emit(l -> l.onConnectionClosed(meta.settings().getTag(), meta.index())); + } catch (Exception e) { + this.logger.warn( + "[{}][{}]: cannot notify about the closed connection", this.machine.identity(), this, e); + } + + // Nobody must wait for a connect that will never happen. + this.machine + .rootConnectFuture() + .completeExceptionally( + outcome.cause() != null + ? outcome.cause() + : new PoolClosedException("Connection is closed: " + this.machine.identity())); + this.machine.rootCloseFuture().complete(null); + this.logger.info("[{}][{}]: session is finished", this.machine.identity(), this); + try { + this.machine.onFinished().accept(outcome); + } catch (Exception e) { + this.logger.error("[{}][{}]: onFinished failed", this.machine.identity(), this, e); + } + } + + /** A connect request that raced with a close: nobody must wait for it. */ + @Override + protected void onConnect(ConnectEvent event) { + logStartHandleEvent(event); + event + .connectFuture() + .completeExceptionally( + new PoolClosedException("Connection is closed: " + this.machine.identity())); + } + + @Override + protected void onClientClose(ClientCloseEvent event) { + logStartHandleEvent(event); + this.machine.linkCloseFuture(event); + } + + // Everything else is stale. + @Override + protected void onRemoteClose(RemoteCloseEvent e) {} + + @Override + protected void onReconnect(ReconnectEvent e) {} +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ClosingState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ClosingState.java new file mode 100644 index 00000000..88dcc48e --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ClosingState.java @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import io.tarantool.pool.PoolEntryState; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.entry.EntryEvent.ClosedEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; + +/** + * Closes the client. The outcome is already known when this state is entered, and the availability + * policy is already stopped (or has never been started): the policy is stopped by {@link + * PolicyStoppingState}, which precedes this state. + * + *

The state hides the connection from the load balancer ({@code CONNECTION_LOST}) and closes the + * client. Every step is guarded on its own and {@link ClosedEvent} is always sent, even if a step + * fails: the session must reach {@code CLOSED}, otherwise the pool entry never gets the finish + * callback and never reconnects. + * + *

All events except {@link ClosedEvent} are ignored here: the reason of the finish is already + * fixed. + */ +final class ClosingState extends EntryState { + + private static final String CONNECTION_LOST_NAME = "CONNECTION_LOST_STATE"; + + /** + * The connection is closed or is being closed, so the entry must be hidden from the load + * balancer. It does not depend on any availability policy. + */ + private static final PoolEntryState CONNECTION_LOST = + new PoolEntryState(CONNECTION_LOST_NAME, true) {}; + + ClosingState(PoolEntryStateMachine machine) { + super(machine, "CLOSING"); + } + + @Override + void enter() { + final PoolEntryView view = this.machine.view(); + this.logger.info( + "[{}][{}]: closing the client, reason: {}", + this.machine.identity(), + this, + describeReason(ctx().outcome)); + + // The session must reach CLOSED whatever fails here: otherwise the entry never gets the finish + // callback, so it never reconnects. Every step is guarded on its own. + // The final state must not depend on the policy: override whatever it has set. + try { + view.changeState(CONNECTION_LOST); + } catch (Exception e) { + this.logger.warn("[{}][{}]: cannot hide the connection", this.machine.identity(), this, e); + } + try { + view.client().close(); + this.logger.info("[{}][{}]: the client is closed", this.machine.identity(), this); + } catch (Exception e) { + this.logger.warn("[{}][{}]: cannot close the client", this.machine.identity(), this, e); + } finally { + this.machine.handle(ClosedEvent.INSTANCE); + } + } + + private static String describeReason(Outcome outcome) { + if (outcome.isClosedByUser()) { + return "closed by user"; + } + final Throwable cause = outcome.cause(); + return cause != null ? cause.toString() : "reconnect requested"; + } + + @Override + protected void onClosed(ClosedEvent event) { + logStartHandleEvent(event); + transitionTo(new ClosedState(this.machine)); + } + + // The reason is already fixed: only the close future must be linked. + @Override + protected void onRemoteClose(EntryEvent.RemoteCloseEvent e) {} + + @Override + protected void onReconnect(EntryEvent.ReconnectEvent e) {} + + @Override + protected void onClientClose(EntryEvent.ClientCloseEvent e) { + logStartHandleEvent(e); + this.machine.linkCloseFuture(e); + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectingState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectingState.java new file mode 100644 index 00000000..0fb7badf --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectingState.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import io.micrometer.core.instrument.LongTaskTimer; + +import io.tarantool.core.IProtoClient; +import io.tarantool.core.utils.CFUtils; +import io.tarantool.pool.InstanceConnectionGroup; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.Metadata; +import io.tarantool.pool.entry.EntryEvent.ConnectErrorEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectedEvent; +import io.tarantool.pool.entry.EntryEvent.RemoteCloseEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; + +/** The client is connecting, authorizing and awaiting the readiness. */ +final class ConnectingState extends EntryState { + + ConnectingState(PoolEntryStateMachine machine) { + super(machine, "CONNECTING"); + } + + @Override + void enter() { + final PoolEntryView view = this.machine.view(); + final Metadata meta = view.metadata(); + final InstanceConnectionGroup group = meta.settings(); + final IProtoClient client = view.client(); + final ConnectionMetrics metrics = this.machine.metrics(); + + this.logger.info("[{}][{}]: connecting to node", this.machine.identity(), this); + final LongTaskTimer.Sample timer = metrics.startConnectTimer(); + try { + client + .connect( + group.getAddress(), this.machine.connectTimeout(), this.machine.gracefulShutdown()) + .thenCompose( + _u -> + group.getUser() != null + ? client.authorize(group.getUser(), group.getPassword(), group.getAuthType()) + : client.ping(PoolEntryStateMachine.FIRST_PING_OPTS)) + .thenCompose(_u -> client.awaitConnectionReady()) + .whenComplete( + (_u, ex) -> { + metrics.stopConnectTimer(timer); + this.machine.handle( + ex == null + ? ConnectedEvent.INSTANCE + : new ConnectErrorEvent(CFUtils.unwrap(ex))); + }); + } catch (Exception e) { + metrics.stopConnectTimer(timer); + this.machine.handle(new ConnectErrorEvent(e)); + } + } + + @Override + protected void onConnected(ConnectedEvent event) { + logStartHandleEvent(event); + this.machine.metrics().connectSucceeded(); + final Metadata meta = this.machine.view().metadata(); + this.logger.info("[POOL_ENTRY][{}][{}]: connected to node", this.machine.identity(), this); + this.machine.view().emit(l -> l.onConnectionOpened(meta.settings().getTag(), meta.index())); + // The connect future is completed without waiting for the policy. + this.machine.rootConnectFuture().complete(this.machine.view().client()); + transitionTo(new PolicyStartingState(this.machine)); + } + + @Override + protected void onConnectError(ConnectErrorEvent event) { + logStartHandleEvent(event); + this.machine.metrics().connectFailed(event.cause()); + this.logger.error( + "[{}][{}]: connect error: {}", this.machine.identity(), this, event.cause().toString()); + // The onConnectionFailed listener event is emitted by the pool entry for every failed session. + beginClosing(Outcome.failed(event.cause())); + } + + /** + * The channel can be closed after the TCP connect but before the greeting: the client then fires + * both the close event and fails the connect future. The control event arrives first, so it must + * be handled as a connect error (metrics, listener); the later {@link ConnectErrorEvent} is + * ignored by the {@code CLOSING} state. + */ + @Override + protected void onRemoteClose(RemoteCloseEvent event) { + final Throwable cause = + event.cause() != null + ? event.cause() + : new IllegalStateException("Connection is closed while connecting"); + onConnectError(new ConnectErrorEvent(cause)); + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectionMetrics.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectionMetrics.java new file mode 100644 index 00000000..91d7be44 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectionMetrics.java @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import io.micrometer.core.instrument.LongTaskTimer; + +/** Metrics callbacks used by a {@link ConnectionSession}. */ +// TODO remove a interface when migrating to Java 9+ using Java modules +public interface ConnectionMetrics { + + /** Does nothing. */ + ConnectionMetrics NOOP = + new ConnectionMetrics() { + @Override + public LongTaskTimer.Sample startConnectTimer() { + return null; + } + + @Override + public void stopConnectTimer(LongTaskTimer.Sample sample) {} + + @Override + public void connectSucceeded() {} + + @Override + public void connectFailed(Throwable cause) {} + }; + + /** Starts measuring the connect time. May return null. */ + LongTaskTimer.Sample startConnectTimer(); + + /** Stops the measurement. The sample may be null. */ + void stopConnectTimer(LongTaskTimer.Sample sample); + + void connectSucceeded(); + + void connectFailed(Throwable cause); +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectionSession.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectionSession.java new file mode 100644 index 00000000..8fe8011f --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/ConnectionSession.java @@ -0,0 +1,99 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.function.Consumer; + +import io.netty.util.Timer; + +import io.tarantool.core.IProtoClient; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.AvailabilityPolicy; +import io.tarantool.pool.entry.EntryEvent.ClientCloseEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectEvent; +import io.tarantool.pool.entry.EntryEvent.ReconnectEvent; +import io.tarantool.pool.entry.EntryEvent.RemoteCloseEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; + +/** + * A one-shot connection session: connect, run the availability policy, close. It is never reused: + * create a new session for every reconnect. This is the only public entry point of the package; the + * machine, its events and states are hidden. + */ +// TODO remove a class when migrating to Java 9+ using Java modules +public final class ConnectionSession { + + private final PoolEntryStateMachine machine; + + public ConnectionSession( + PoolEntryView view, + AvailabilityPolicy policy, + Timer timer, + long connectTimeout, + boolean gracefulShutdown, + ConnectionMetrics metrics, + Consumer onFinished) { + Objects.requireNonNull(onFinished, "onFinished must not be null"); + this.machine = + new PoolEntryStateMachine( + view, + policy, + timer, + connectTimeout, + gracefulShutdown, + metrics, + o -> onFinished.accept(new SessionOutcome(o))); + } + + /** + * Starts the connection process. The returned future is completed when the client is connected + * (without waiting for the policy) and fails if the session finishes before that. Call it once. + */ + public CompletableFuture connect() { + final CompletableFuture cf = new CompletableFuture<>(); + this.machine.handle(new ConnectEvent(cf)); + return cf; + } + + /** Closes the session for good. The future completes when the session is finished. */ + public CompletableFuture close() { + final CompletableFuture cf = new CompletableFuture<>(); + this.machine.handle(new ClientCloseEvent(cf)); + return cf; + } + + /** Asks the session to recycle the connection. The cause may be null. */ + public void reconnect(Throwable cause) { + this.machine.handle(new ReconnectEvent(cause)); + } + + /** Notifies the session that the connection was closed by the remote side or by a shutdown. */ + public void remoteClosed(Throwable cause) { + this.machine.handle(new RemoteCloseEvent(cause)); + } + + /** The reason why a session has finished. */ + public static final class SessionOutcome { + + private final Outcome outcome; + + private SessionOutcome(Outcome outcome) { + this.outcome = outcome; + } + + /** True if the entry was closed on purpose and must not reconnect. */ + public boolean isClosedByUser() { + return this.outcome.isClosedByUser(); + } + + /** May be null. */ + public Throwable cause() { + return this.outcome.cause(); + } + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/EntryEvent.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/EntryEvent.java index 125aeb93..f7cac3b1 100644 --- a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/EntryEvent.java +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/EntryEvent.java @@ -141,8 +141,9 @@ Throwable cause() { *

Sent by: {@code PolicyStartingState}, when the stage returned by the policy completes * normally. * - *

Handled by: {@code PolicyStartingState}: moves to {@code ACTIVE}. Other states ignore - * it. This is also the case when a close request has arrived while the policy was starting. + *

Handled by: {@code PolicyStartingState}: moves to {@code RUNNING}. Other states + * ignore it. This is also the case when a close request has arrived while the policy was + * starting. * *

It has no payload, so a single shared instance is used. */ @@ -251,11 +252,13 @@ private BackoffElapsedEvent() { * pool entry owner. Those start the closing, this one reports that the session has * finished closing. * - *

Sent by: {@code ClosingState}, when {@code client.close()} has been called. + *

Sent by: {@code ClosingState}, after the attempt to close the client. It is sent even + * if hiding the connection or closing the client has failed (the failure is logged), so the + * session always reaches {@code CLOSED}. * *

Handled by: {@code ClosingState}: moves to the terminal {@code CLOSED} state, which - * completes the futures, emits {@code onConnectionClosed} and notifies the owner about the - * outcome. Other states ignore it. + * emits {@code onConnectionClosed} (a failure of the listener is logged and ignored), completes + * the futures and notifies the owner about the outcome. Other states ignore it. * *

It has no payload, so a single shared instance is used. */ diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/EntryState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/EntryState.java new file mode 100644 index 00000000..e65ce8f3 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/EntryState.java @@ -0,0 +1,145 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.tarantool.core.state.State; +import io.tarantool.pool.entry.EntryEvent.BackoffElapsedEvent; +import io.tarantool.pool.entry.EntryEvent.ClientCloseEvent; +import io.tarantool.pool.entry.EntryEvent.ClosedEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectErrorEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectedEvent; +import io.tarantool.pool.entry.EntryEvent.PolicyStartErrorEvent; +import io.tarantool.pool.entry.EntryEvent.PolicyStartedEvent; +import io.tarantool.pool.entry.EntryEvent.PolicyStoppedEvent; +import io.tarantool.pool.entry.EntryEvent.ReconnectEvent; +import io.tarantool.pool.entry.EntryEvent.RemoteCloseEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.ConnectionCtx; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; + +/** + * The base class of the states of the one-shot connection machine. Events that are not meaningful + * for a state are ignored by default (this is how stale events are dropped). + */ +abstract class EntryState implements State { + + protected final Logger logger = LoggerFactory.getLogger(getClass()); + + protected final PoolEntryStateMachine machine; + private final String name; + + EntryState(PoolEntryStateMachine machine, String name) { + this.machine = machine; + this.name = name; + } + + @Override + public void handle(EntryEvent event) { + if (event == null) { + this.logger.debug("[{}][{}]: got a null event. Skipping...", machine.identity(), this); + return; + } + this.logger.debug("[{}][{}]: received '{}' event", machine.identity(), this, event); + + if (event instanceof ConnectEvent) onConnect((ConnectEvent) event); + else if (event instanceof ConnectedEvent) onConnected((ConnectedEvent) event); + else if (event instanceof ConnectErrorEvent) onConnectError((ConnectErrorEvent) event); + else if (event instanceof PolicyStartedEvent) onPolicyStarted((PolicyStartedEvent) event); + else if (event instanceof PolicyStartErrorEvent) + onPolicyStartError((PolicyStartErrorEvent) event); + else if (event instanceof PolicyStoppedEvent) onPolicyStopped((PolicyStoppedEvent) event); + else if (event instanceof BackoffElapsedEvent) onBackoffElapsed((BackoffElapsedEvent) event); + else if (event instanceof ClosedEvent) onClosed((ClosedEvent) event); + else if (event instanceof RemoteCloseEvent) onRemoteClose((RemoteCloseEvent) event); + else if (event instanceof ReconnectEvent) onReconnect((ReconnectEvent) event); + else if (event instanceof ClientCloseEvent) onClientClose((ClientCloseEvent) event); + else + this.logger.debug( + "[{}][{}]: received an unexpected '{}' event", machine.identity(), this, event); + } + + /** Entry action. It is invoked by {@link #transitionTo(EntryState)}. */ + void enter() {} + + protected void onConnect(ConnectEvent e) {} + + protected void onConnected(ConnectedEvent e) {} + + protected void onConnectError(ConnectErrorEvent e) {} + + protected void onPolicyStarted(PolicyStartedEvent e) {} + + protected void onPolicyStartError(PolicyStartErrorEvent e) {} + + protected void onPolicyStopped(PolicyStoppedEvent e) {} + + protected void onBackoffElapsed(BackoffElapsedEvent e) {} + + protected void onClosed(ClosedEvent e) {} + + /** By default, a connection loss closes the session (see {@link #beginClosing(Outcome)}). */ + protected void onRemoteClose(RemoteCloseEvent e) { + logStartHandleEvent(e); + beginClosing(Outcome.failed(e.cause())); + } + + /** By default, a reconnect request closes the session. */ + protected void onReconnect(ReconnectEvent e) { + logStartHandleEvent(e); + beginClosing(Outcome.failed(e.cause())); + } + + /** By default, a close request closes the session. */ + protected void onClientClose(ClientCloseEvent e) { + logStartHandleEvent(e); + this.machine.linkCloseFuture(e); + beginClosing(Outcome.closed()); + } + + protected final ConnectionCtx ctx() { + return this.machine.ctx(); + } + + protected final void logStartHandleEvent(EntryEvent event) { + this.logger.debug("[{}][{}]: start handle '{}' event", this.machine.identity(), this, event); + } + + protected final void transitionTo(EntryState nextState) { + this.machine.state(nextState); + this.logger.debug( + "[{}][{}]: transitioned to '{}' state", this.machine.identity(), this, nextState); + nextState.enter(); + } + + /** + * Starts finishing the session with the given outcome. The first outcome wins: if the session is + * already finishing for some reason, the later reasons are ignored. + * + *

If the availability policy has been started, it must be stopped first, so the machine moves + * to {@code STOPPING}, which then moves to {@code CLOSING}. Otherwise, it moves to {@code + * CLOSING} at once. + */ + protected final void beginClosing(Outcome outcome) { + final ConnectionCtx ctx = ctx(); + if (ctx.outcome == null) { + ctx.outcome = outcome; + } + ctx.cancelBackoff(); + if (ctx.policyNeedsStop) { + transitionTo(new PolicyStoppingState(this.machine)); + } else { + transitionTo(new ClosingState(this.machine)); + } + } + + @Override + public String toString() { + return this.name; + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/InitState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/InitState.java new file mode 100644 index 00000000..f22db761 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/InitState.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import io.tarantool.core.utils.CFUtils; +import io.tarantool.pool.entry.EntryEvent.ClientCloseEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; + +/** The initial state: nothing has been done yet. */ +final class InitState extends EntryState { + + InitState(PoolEntryStateMachine machine) { + super(machine, "INIT"); + } + + @Override + protected void onConnect(ConnectEvent event) { + logStartHandleEvent(event); + CFUtils.linkFuture(this.machine.rootConnectFuture(), event.connectFuture()); + transitionTo(new ConnectingState(this.machine)); + } + + /** Nothing to release: go straight to the terminal state. */ + @Override + protected void onClientClose(ClientCloseEvent event) { + logStartHandleEvent(event); + this.machine.linkCloseFuture(event); + ctx().outcome = Outcome.closed(); + transitionTo(new ClosedState(this.machine)); + } + + // conn_closed / reconnect before connect are meaningless: ignore. + @Override + protected void onRemoteClose(EntryEvent.RemoteCloseEvent e) {} + + @Override + protected void onReconnect(EntryEvent.ReconnectEvent e) {} +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyRestartingState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyRestartingState.java new file mode 100644 index 00000000..e7deea2f --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyRestartingState.java @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import java.time.Duration; + +import io.tarantool.pool.entry.EntryEvent.BackoffElapsedEvent; + +/** The policy is stopped and waits for {@code restartBackoff} before the next start. */ +final class PolicyRestartingState extends EntryState { + + PolicyRestartingState(PoolEntryStateMachine machine) { + super(machine, "POLICY_RESTARTING"); + } + + @Override + void enter() { + Duration backoff; + try { + backoff = this.machine.policy().restartBackoff(this.machine.view()); + } catch (Exception e) { + this.logger.warn( + "[{}][{}]: restartBackoff failed, using zero", this.machine.identity(), this, e); + backoff = null; + } + final Duration delay = backoff == null ? Duration.ZERO : backoff; + this.logger.info("[{}][{}]: restart policy after {}", this.machine.identity(), this, delay); + ctx().scheduleBackoff(delay); + } + + @Override + protected void onBackoffElapsed(BackoffElapsedEvent event) { + logStartHandleEvent(event); + ctx().backoffTask = null; + transitionTo(new PolicyStartingState(this.machine)); + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyStartingState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyStartingState.java new file mode 100644 index 00000000..0e7f0836 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyStartingState.java @@ -0,0 +1,58 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import io.tarantool.core.utils.CFUtils; +import io.tarantool.pool.entry.EntryEvent.PolicyStartErrorEvent; +import io.tarantool.pool.entry.EntryEvent.PolicyStartedEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.ConnectionCtx; + +/** {@code AvailabilityPolicy.start} is in flight. */ +final class PolicyStartingState extends EntryState { + + PolicyStartingState(PoolEntryStateMachine machine) { + super(machine, "POLICY_STARTING"); + } + + @Override + void enter() { + final ConnectionCtx ctx = ctx(); + ctx.policyNeedsStop = true; + ctx.policyError = null; + this.logger.info("[POOL_ENTRY][{}][{}]: start policy", this.machine.identity(), this); + try { + this.machine + .policy() + .start(this.machine.view()) + .whenComplete( + (_u, ex) -> + this.machine.handle( + ex == null + ? PolicyStartedEvent.INSTANCE + : new PolicyStartErrorEvent(CFUtils.unwrap(ex)))); + } catch (Exception e) { + this.machine.handle(new PolicyStartErrorEvent(e)); + } + } + + @Override + protected void onPolicyStarted(PolicyStartedEvent event) { + logStartHandleEvent(event); + transitionTo(new RunningState(this.machine)); + } + + @Override + protected void onPolicyStartError(PolicyStartErrorEvent event) { + logStartHandleEvent(event); + this.logger.warn( + "[{}][{}]: policy start failed: {}", + this.machine.identity(), + this, + event.cause().toString()); + ctx().policyError = event.cause(); + transitionTo(new PolicyStoppingState(this.machine)); + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyStoppingState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyStoppingState.java new file mode 100644 index 00000000..3e2a2af6 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PolicyStoppingState.java @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import io.tarantool.core.utils.CFUtils; +import io.tarantool.pool.entry.EntryEvent.ClientCloseEvent; +import io.tarantool.pool.entry.EntryEvent.PolicyStoppedEvent; +import io.tarantool.pool.entry.EntryEvent.ReconnectEvent; +import io.tarantool.pool.entry.EntryEvent.RemoteCloseEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.ConnectionCtx; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; + +/** + * {@code AvailabilityPolicy.stop} is in flight. The state is entered in two cases: + * + *

+ * + *

If a reason to finish the session comes while the stop is in flight, the state remembers the + * outcome and waits for the stop to finish instead of calling {@code stop} twice. + */ +final class PolicyStoppingState extends EntryState { + + PolicyStoppingState(PoolEntryStateMachine machine) { + super(machine, "POLICY_STOPPING"); + } + + @Override + void enter() { + final ConnectionCtx ctx = ctx(); + // The reason of the stop: the session finish or, if there is none, the failed policy start. + final Throwable cause = ctx.outcome != null ? ctx.outcome.cause() : ctx.policyError; + this.logger.info( + "[POOL_ENTRY][{}][{}]: stop the availability policy", this.machine.identity(), this); + try { + this.machine + .policy() + .stop(this.machine.view(), cause) + .whenComplete( + (_u, ex) -> this.machine.handle(new PolicyStoppedEvent(CFUtils.unwrap(ex)))); + } catch (Exception e) { + this.machine.handle(new PolicyStoppedEvent(e)); + } + } + + @Override + protected void onPolicyStopped(PolicyStoppedEvent event) { + logStartHandleEvent(event); + if (event.cause() != null) { + this.logger.warn( + "[POOL_ENTRY][{}][{}]: policy stop failed: {}", + this.machine.identity(), + this, + event.cause().toString()); + } else { + this.logger.info( + "[POOL_ENTRY][{}][{}]: the availability policy is stopped", + this.machine.identity(), + this); + } + final ConnectionCtx ctx = ctx(); + ctx.policyNeedsStop = false; + if (ctx.outcome != null) { + // The session is being finished: only the client is left to close. + transitionTo(new ClosingState(this.machine)); + } else { + transitionTo(new PolicyRestartingState(this.machine)); + } + } + + @Override + protected void onRemoteClose(RemoteCloseEvent e) { + logStartHandleEvent(e); + rememberOutcome(Outcome.failed(e.cause())); + } + + @Override + protected void onReconnect(ReconnectEvent e) { + logStartHandleEvent(e); + rememberOutcome(Outcome.failed(e.cause())); + } + + @Override + protected void onClientClose(ClientCloseEvent e) { + logStartHandleEvent(e); + this.machine.linkCloseFuture(e); + rememberOutcome(Outcome.closed()); + } + + private void rememberOutcome(Outcome outcome) { + if (ctx().outcome == null) { + ctx().outcome = outcome; + } + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PoolEntryStateMachine.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PoolEntryStateMachine.java new file mode 100644 index 00000000..6bacfec9 --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/PoolEntryStateMachine.java @@ -0,0 +1,221 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.TimeUnit; +import java.util.function.Consumer; + +import io.netty.util.Timeout; +import io.netty.util.Timer; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.tarantool.core.IProtoClient; +import io.tarantool.core.protocol.IProtoRequestOpts; +import io.tarantool.core.state.AbstractDrainLoopMachine; +import io.tarantool.core.utils.CFUtils; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.AvailabilityPolicy; +import io.tarantool.pool.availability.Metadata; +import io.tarantool.pool.entry.EntryEvent.BackoffElapsedEvent; +import io.tarantool.pool.entry.EntryEvent.ClientCloseEvent; +import io.tarantool.pool.entry.EntryEvent.ReconnectEvent; + +/** + * The one-shot machine of a single connection session of {@link PoolEntry}: it lives from the first + * connect attempt until the connection is closed and is never reused. The entry creates a new + * machine for every reconnect. + * + *

The machine owns the policy lifecycle ({@code start}/{@code stop}/{@code restartBackoff}) for + * the session. The reconnect delay and the creation of the next session are the entry's concern. + */ +final class PoolEntryStateMachine extends AbstractDrainLoopMachine { + + private static final Logger LOGGER = LoggerFactory.getLogger(PoolEntryStateMachine.class); + + /** IProto options for the first request that checks the connection liveness. */ + static final IProtoRequestOpts FIRST_PING_OPTS = + IProtoRequestOpts.empty().withRequestTimeout(1000); + + private final PoolEntryView view; + private final AvailabilityPolicy policy; + private final Timer timer; + private final long connectTimeout; + private final boolean gracefulShutdown; + private final ConnectionMetrics metrics; + private final Consumer onFinished; + private final String identity; + + private final CompletableFuture rootConnectFuture = new CompletableFuture<>(); + private final CompletableFuture rootCloseFuture = new CompletableFuture<>(); + private final ConnectionCtx ctx = new ConnectionCtx(); + private volatile EntryState state = new InitState(this); + + /** + * @param onFinished is called exactly once, when the machine reaches the terminal state. It is + * called from the machine's event loop, so it must not block. + */ + PoolEntryStateMachine( + PoolEntryView view, + AvailabilityPolicy policy, + Timer timer, + long connectTimeout, + boolean gracefulShutdown, + ConnectionMetrics metrics, + Consumer onFinished) { + this.view = Objects.requireNonNull(view, "view must not be null"); + this.policy = Objects.requireNonNull(policy, "policy must not be null"); + this.timer = Objects.requireNonNull(timer, "timer must not be null"); + this.onFinished = Objects.requireNonNull(onFinished, "onFinished must not be null"); + this.connectTimeout = connectTimeout; + this.gracefulShutdown = gracefulShutdown; + this.metrics = metrics != null ? metrics : ConnectionMetrics.NOOP; + + final Metadata metadata = view.metadata(); + this.identity = metadata.settings().getTag() + '/' + metadata.index(); + } + + @Override + protected void processEvent(EntryEvent event) { + this.state.handle(event); + } + + @Override + protected void onHandleError(Throwable error) { + LOGGER.warn( + "[{}]: caught an unexpected error while handling an event. Recycling the connection...", + this, + error); + // No-op for the closing/closed states: the first outcome wins. + handle(new ReconnectEvent(error)); + } + + void linkCloseFuture(ClientCloseEvent event) { + CFUtils.linkFuture(this.rootCloseFuture, event.closeFuture()); + } + + void state(EntryState newState) { + this.state = newState; + } + + EntryState state() { + return this.state; + } + + ConnectionCtx ctx() { + return this.ctx; + } + + PoolEntryView view() { + return this.view; + } + + AvailabilityPolicy policy() { + return this.policy; + } + + long connectTimeout() { + return this.connectTimeout; + } + + boolean gracefulShutdown() { + return this.gracefulShutdown; + } + + ConnectionMetrics metrics() { + return this.metrics; + } + + Consumer onFinished() { + return this.onFinished; + } + + CompletableFuture rootConnectFuture() { + return this.rootConnectFuture; + } + + CompletableFuture rootCloseFuture() { + return this.rootCloseFuture; + } + + String identity() { + return this.identity; + } + + @Override + public String toString() { + return '[' + this.identity + "][PoolEntryStateMachine]"; + } + + /** Reason why the session has finished. */ + static final class Outcome { + + private static final Outcome CLOSED = new Outcome(true, null); + + private final boolean closedByUser; + private final Throwable cause; + + private Outcome(boolean closedByUser, Throwable cause) { + this.closedByUser = closedByUser; + this.cause = cause; + } + + /** The entry was closed on purpose: the entry must not reconnect. */ + static Outcome closed() { + return CLOSED; + } + + /** + * The connection was lost or recycled: the entry must reconnect after {@code reconnectAfter}. + */ + static Outcome failed(Throwable cause) { + return new Outcome(false, CFUtils.unwrap(cause)); + } + + boolean isClosedByUser() { + return this.closedByUser; + } + + Throwable cause() { + return this.cause; + } + } + + /** + * The mutable part of the machine state. It is shared between the states and must be accessible + * for them without any restrictions. + */ + final class ConnectionCtx { + + /** True between the {@code policy.start} call and the finished {@code policy.stop}. */ + boolean policyNeedsStop; + + /** The error of the last failed policy start. It is passed to {@code policy.stop}. */ + Throwable policyError; + + /** The reason of the session finish. It is set once, by the first reason. */ + Outcome outcome; + + Timeout backoffTask; + + void scheduleBackoff(Duration delay) { + cancelBackoff(); + this.backoffTask = + timer.newTimeout( + _u -> handle(BackoffElapsedEvent.INSTANCE), delay.toNanos(), TimeUnit.NANOSECONDS); + } + + void cancelBackoff() { + if (this.backoffTask != null) { + this.backoffTask.cancel(); + this.backoffTask = null; + } + } + } +} diff --git a/tarantool-pooling/src/main/java/io/tarantool/pool/entry/RunningState.java b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/RunningState.java new file mode 100644 index 00000000..2e8c5efb --- /dev/null +++ b/tarantool-pooling/src/main/java/io/tarantool/pool/entry/RunningState.java @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import io.tarantool.pool.PoolEntryState; +import io.tarantool.pool.PoolEntryView; + +/** + * The connection is established and the policy is running. The policy drives the availability via + * {@link PoolEntryView#changeState(PoolEntryState)}; this state only waits for a reason to close. + * Connection loss, reconnect and close requests are handled by the base class. + */ +final class RunningState extends EntryState { + + RunningState(PoolEntryStateMachine machine) { + super(machine, "RUNNING"); + } + + @Override + void enter() { + this.logger.info( + "[POOL_ENTRY][{}][{}]: connection is established and availability policy is started", + this.machine.identity(), + this); + } +} diff --git a/tarantool-pooling/src/main/resources/schemas/pool-entry/PoolEntry.puml b/tarantool-pooling/src/main/resources/schemas/pool-entry/PoolEntry.puml new file mode 100644 index 00000000..85546eb2 --- /dev/null +++ b/tarantool-pooling/src/main/resources/schemas/pool-entry/PoolEntry.puml @@ -0,0 +1,43 @@ + @startuml + + [*] --> INIT + + state INIT + state CONNECTING : entry / connect -> authorize|ping -> awaitReady + state POLICY_STARTING : entry / policy.start(view) + state ACTIVE : the policy drives the availability + state POLICY_STOPPING : entry / policy.stop(view, cause)\nControl events only remember the outcome + state POLICY_RESTARTING : entry / schedule restartBackoff timer + state CLOSING : entry / state = CONNECTION_LOST, client.close() + state CLOSED <> : entry / complete futures, emit onConnectionClosed, onFinished(outcome) + + INIT --> CONNECTING : CONNECT_EVT + INIT --> CLOSED : CLIENT_CLOSE_EVT + + CONNECTING --> POLICY_STARTING : CONNECTED_EVT / complete connect future + CONNECTING --> CLOSING : CONNECT_ERROR_EVT |\nREMOTE_CLOSE_EVT |\nRECONNECT_EVT |\nCLIENT_CLOSE_EVT \n/ outcome + + POLICY_STARTING --> ACTIVE : POLICY_STARTED_EVT + POLICY_STARTING --> POLICY_STOPPING : POLICY_START_ERROR_EVT\n/ remember policyError + POLICY_STARTING --> POLICY_STOPPING : REMOTE_CLOSE_EVT |\nRECONNECT_EVT |\nCLIENT_CLOSE_EVT\n/ outcome + + ACTIVE --> POLICY_STOPPING : REMOTE_CLOSE_EVT |\nRECONNECT_EVT |\nCLIENT_CLOSE_EVT\n/ outcome + + POLICY_STOPPING --> POLICY_RESTARTING : POLICY_STOPPED_EVT\n[no outcome] + POLICY_STOPPING --> CLOSING : POLICY_STOPPED_EVT\n[outcome is set] + POLICY_STOPPING --> POLICY_STOPPING : REMOTE_CLOSE_EVT |\nRECONNECT_EVT |\nCLIENT_CLOSE_EVT\n/ remember outcome + + POLICY_RESTARTING --> POLICY_STARTING : BACKOFF_ELAPSED_EVT + POLICY_RESTARTING --> CLOSING : REMOTE_CLOSE_EVT |\nRECONNECT_EVT |\nCLIENT_CLOSE_EVT\n/ cancel backoff, outcome + + CLOSING --> CLOSED : CLOSED_EVT + CLOSING --> CLOSING : CLIENT_CLOSE_EVT / link close future + + CLOSED --> CLOSED : CLIENT_CLOSE_EVT / link close future\nConnectEvent / fail connect future + CLOSED --> [*] + + note left of CLOSED + outcome = closed() -> PoolEntry does not reconnect + outcome = failed(c) -> PoolEntry reconnects after reconnectAfter + end note + @enduml From bd37195d25decad1bf8eafcc6f5e215a918d5913 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=BE=D0=BB=D0=B0=D0=B9=20=D0=91=D0=B5?= =?UTF-8?q?=D0=BB=D0=BE=D0=BD=D0=BE=D0=B3=D0=BE=D0=B2?= Date: Mon, 30 Nov 2026 14:47:38 +0300 Subject: [PATCH 2/2] test(pool): add PoolEntryStateMachine tests --- .../PoolEntryStateMachineMatrixTest.java | 324 +++++ .../pool/entry/PoolEntryStateMachineTest.java | 1141 +++++++++++++++++ .../pool/support/RecordingPoolEntryView.java | 96 +- .../pool/support/ScriptedPolicy.java | 170 +++ .../io/tarantool/pool/support/StubClient.java | 202 +++ 5 files changed, 1927 insertions(+), 6 deletions(-) create mode 100644 tarantool-pooling/src/test/java/io/tarantool/pool/entry/PoolEntryStateMachineMatrixTest.java create mode 100644 tarantool-pooling/src/test/java/io/tarantool/pool/entry/PoolEntryStateMachineTest.java create mode 100644 tarantool-pooling/src/test/java/io/tarantool/pool/support/ScriptedPolicy.java diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/entry/PoolEntryStateMachineMatrixTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/entry/PoolEntryStateMachineMatrixTest.java new file mode 100644 index 00000000..ab779cd5 --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/entry/PoolEntryStateMachineMatrixTest.java @@ -0,0 +1,324 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import java.time.Duration; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.TimeUnit; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInstance; +import org.junit.jupiter.api.TestInstance.Lifecycle; +import org.junit.jupiter.api.Timeout; +import org.junit.jupiter.api.parallel.Execution; +import org.junit.jupiter.api.parallel.ExecutionMode; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import io.tarantool.pool.entry.EntryEvent.BackoffElapsedEvent; +import io.tarantool.pool.entry.EntryEvent.ClientCloseEvent; +import io.tarantool.pool.entry.EntryEvent.ClosedEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectErrorEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectedEvent; +import io.tarantool.pool.entry.EntryEvent.PolicyStartErrorEvent; +import io.tarantool.pool.entry.EntryEvent.PolicyStartedEvent; +import io.tarantool.pool.entry.EntryEvent.PolicyStoppedEvent; +import io.tarantool.pool.entry.EntryEvent.ReconnectEvent; +import io.tarantool.pool.entry.EntryEvent.RemoteCloseEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; +import io.tarantool.pool.support.FakeTimer; +import io.tarantool.pool.support.RecordingPoolEntryView; +import io.tarantool.pool.support.ScriptedPolicy; +import io.tarantool.pool.support.StubClient; + +/** + * The matrix test of {@link PoolEntryStateMachine}: every event is sent to every state. + * + *

Each cell checks two things. First, the state the machine moves to after the event (events + * that are meaningless for a state must be ignored, so the state does not change). Second, the + * invariants that must hold whatever has happened: after a close request the machine always reaches + * the final state, the session is finished exactly once, the close future is completed, the client + * is closed at most once and every start of the policy is paired with a stop. + * + *

The stubs complete the futures at once, so the machine passes the transient states inside a + * single {@code handle} call. The states where the machine has to wait are prepared with pending + * futures, which the test completes in the end. + */ +@Timeout(value = 10, unit = TimeUnit.SECONDS) +@TestInstance(Lifecycle.PER_METHOD) +@Execution(ExecutionMode.SAME_THREAD) +public class PoolEntryStateMachineMatrixTest { + + /** The states the machine is prepared in. The transient closing state cannot be observed. */ + enum Setup { + INIT, + CONNECTING, + POLICY_STARTING, + RUNNING, + /** The policy is being stopped because the session is being finished. */ + POLICY_STOPPING_FINISHING, + /** The policy is being stopped after a failed start and will be restarted. */ + POLICY_STOPPING_AFTER_FAILED_START, + POLICY_RESTARTING, + CLOSED + } + + /** The events the machine may receive. */ + enum Ev { + CONNECT, + CONNECTED, + CONNECT_ERROR, + POLICY_STARTED, + POLICY_START_ERROR, + POLICY_STOPPED, + BACKOFF_ELAPSED, + CLOSED_EVENT, + REMOTE_CLOSE, + RECONNECT, + CLIENT_CLOSE; + + boolean isControl() { + return this == REMOTE_CLOSE || this == RECONNECT || this == CLIENT_CLOSE; + } + } + + private StubClient client; + private ScriptedPolicy policy; + private List finished; + private PoolEntryStateMachine machine; + private final List> pending = new CopyOnWriteArrayList<>(); + + @BeforeEach + void setUp() { + FakeTimer timer = new FakeTimer(); + this.client = StubClient.create(); + this.policy = new ScriptedPolicy(); + RecordingPoolEntryView view = + RecordingPoolEntryView.create("node-a", 0, this.policy, this.client.client()); + this.finished = new CopyOnWriteArrayList<>(); + this.machine = + new PoolEntryStateMachine( + view, this.policy, timer, 1_000L, true, ConnectionMetrics.NOOP, this.finished::add); + } + + static Stream cells() { + final Stream.Builder cells = Stream.builder(); + for (final Setup setup : Setup.values()) { + for (final Ev event : Ev.values()) { + cells.add(Arguments.of(setup, event)); + } + } + return cells.build(); + } + + @ParameterizedTest(name = "{0} + {1}") + @MethodSource("cells") + void testEventInState(Setup setup, Ev event) { + prepare(setup); + Assertions.assertInstanceOf( + initialState(setup), this.machine.state(), "The machine is prepared in a wrong state"); + + Assertions.assertDoesNotThrow(() -> this.machine.handle(create(event))); + + Assertions.assertInstanceOf( + expected(setup, event), + this.machine.state(), + "Wrong state after " + event + " in " + setup); + + assertCanBeClosed(); + } + + /* + ********************************************************** + * The expected transitions + ********************************************************** + */ + + private static Class initialState(Setup setup) { + switch (setup) { + case INIT: + return InitState.class; + case CONNECTING: + return ConnectingState.class; + case POLICY_STARTING: + return PolicyStartingState.class; + case RUNNING: + return RunningState.class; + case POLICY_STOPPING_FINISHING: + case POLICY_STOPPING_AFTER_FAILED_START: + return PolicyStoppingState.class; + case POLICY_RESTARTING: + return PolicyRestartingState.class; + default: + return ClosedState.class; + } + } + + /** + * The state after the event. The stubs complete the futures at once, so a transition that goes + * through the transient states ends in the state that follows them. + */ + private static Class expected(Setup setup, Ev event) { + switch (setup) { + case INIT: + if (event == Ev.CONNECT) { + // connect, start of the policy: everything completes at once + return RunningState.class; + } + return event == Ev.CLIENT_CLOSE ? ClosedState.class : InitState.class; + case CONNECTING: + if (event == Ev.CONNECTED) { + return RunningState.class; + } + return event == Ev.CONNECT_ERROR || event.isControl() + ? ClosedState.class + : ConnectingState.class; + case POLICY_STARTING: + if (event == Ev.POLICY_STARTED) { + return RunningState.class; + } + if (event == Ev.POLICY_START_ERROR) { + // the stop completes at once, so the machine waits for the restart backoff + return PolicyRestartingState.class; + } + return event.isControl() ? ClosedState.class : PolicyStartingState.class; + case RUNNING: + return event.isControl() ? ClosedState.class : RunningState.class; + case POLICY_STOPPING_FINISHING: + // the outcome is known: the end of the stop leads to the close + return event == Ev.POLICY_STOPPED ? ClosedState.class : PolicyStoppingState.class; + case POLICY_STOPPING_AFTER_FAILED_START: + // no outcome yet: the end of the stop leads to the restart, the control events are only + // remembered + return event == Ev.POLICY_STOPPED ? PolicyRestartingState.class : PolicyStoppingState.class; + case POLICY_RESTARTING: + if (event == Ev.BACKOFF_ELAPSED) { + return RunningState.class; + } + return event.isControl() ? ClosedState.class : PolicyRestartingState.class; + default: + return ClosedState.class; + } + } + + /* + ********************************************************** + * The preparation of the states and the events + ********************************************************** + */ + + private void prepare(Setup setup) { + switch (setup) { + case INIT: + break; + case CONNECTING: + this.client.connectReturns(pendingFuture()); + connect(); + break; + case POLICY_STARTING: + this.policy.nextStartReturns(pendingFuture()); + connect(); + break; + case RUNNING: + connect(); + break; + case POLICY_STOPPING_FINISHING: + connect(); + this.policy.nextStopReturns(pendingFuture()); + this.machine.handle(new ReconnectEvent(new IllegalStateException("first"))); + break; + case POLICY_STOPPING_AFTER_FAILED_START: + this.policy.nextStartFails(new IllegalStateException("start failed")); + this.policy.nextStopReturns(pendingFuture()); + connect(); + break; + case POLICY_RESTARTING: + this.policy.backoff(Duration.ofSeconds(5)); + this.policy.nextStartFails(new IllegalStateException("start failed")); + connect(); + break; + default: + connect(); + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + } + } + + private static EntryEvent create(Ev event) { + switch (event) { + case CONNECT: + return new ConnectEvent(new CompletableFuture<>()); + case CONNECTED: + return ConnectedEvent.INSTANCE; + case CONNECT_ERROR: + return new ConnectErrorEvent(new IllegalStateException("connect failed")); + case POLICY_STARTED: + return PolicyStartedEvent.INSTANCE; + case POLICY_START_ERROR: + return new PolicyStartErrorEvent(new IllegalStateException("start failed")); + case POLICY_STOPPED: + return new PolicyStoppedEvent(null); + case BACKOFF_ELAPSED: + return BackoffElapsedEvent.INSTANCE; + case CLOSED_EVENT: + return ClosedEvent.INSTANCE; + case REMOTE_CLOSE: + return new RemoteCloseEvent(new IllegalStateException("remote close")); + case RECONNECT: + return new ReconnectEvent(new IllegalStateException("reconnect")); + default: + return new ClientCloseEvent(new CompletableFuture<>()); + } + } + + private CompletableFuture pendingFuture() { + final CompletableFuture future = new CompletableFuture<>(); + this.pending.add(future); + return future; + } + + private void connect() { + this.machine.handle(new ConnectEvent(new CompletableFuture<>())); + } + + /* + ********************************************************** + * The invariants + ********************************************************** + */ + + /** + * Closes the machine, completes everything it may wait for and checks the invariants that must + * hold whatever has happened before. + */ + private void assertCanBeClosed() { + final CompletableFuture closeFuture = new CompletableFuture<>(); + + this.machine.handle(new ClientCloseEvent(closeFuture)); + for (final CompletableFuture future : this.pending) { + future.complete(null); + } + + Assertions.assertInstanceOf( + ClosedState.class, this.machine.state(), "The machine must reach the final state"); + Assertions.assertEquals(1, this.finished.size(), "The session must be finished exactly once"); + Assertions.assertNotNull(this.finished.get(0), "The outcome must be set"); + Assertions.assertTrue(closeFuture.isDone(), "The close future must be completed"); + Assertions.assertTrue(this.client.closeCalls() <= 1, "The client must be closed at most once"); + final List calls = this.policy.calls(); + for (int i = 0; i < calls.size(); i++) { + Assertions.assertEquals( + i % 2 == 0 ? "start" : "stop", calls.get(i), "The policy calls must alternate: " + calls); + } + Assertions.assertEquals( + 0, calls.size() % 2, "Every start must be paired with a stop: " + calls); + } +} diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/entry/PoolEntryStateMachineTest.java b/tarantool-pooling/src/test/java/io/tarantool/pool/entry/PoolEntryStateMachineTest.java new file mode 100644 index 00000000..5506e2b2 --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/entry/PoolEntryStateMachineTest.java @@ -0,0 +1,1141 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.entry; + +import java.io.IOException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionException; +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.concurrent.atomic.AtomicInteger; +import java.util.function.Consumer; + +import io.micrometer.core.instrument.LongTaskTimer; +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.Mockito; + +import io.tarantool.core.IProtoClient; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.entry.EntryEvent.ClientCloseEvent; +import io.tarantool.pool.entry.EntryEvent.ConnectEvent; +import io.tarantool.pool.entry.PoolEntryStateMachine.Outcome; +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.ScriptedPolicy; +import io.tarantool.pool.support.StubClient; + +@TestInstance(Lifecycle.PER_METHOD) +@Execution(ExecutionMode.CONCURRENT) +@Timeout(value = 10, unit = TimeUnit.SECONDS) +public class PoolEntryStateMachineTest { + + private static final String TAG = "node-a"; + private static final int IDX = 0; + private static final String CONNECTION_LOST_STATE = "CONNECTION_LOST_STATE"; + + private FakeTimer timer; + private StubClient client; + private ScriptedPolicy policy; + private RecordingPoolEntryView view; + private RecordingMetrics metrics; + private List finished; + private PoolEntryStateMachine machine; + + @BeforeEach + void setUp() { + this.timer = new FakeTimer(); + this.client = StubClient.create(); + this.policy = new ScriptedPolicy(); + this.view = RecordingPoolEntryView.create(TAG, IDX, this.policy, this.client.client()); + this.metrics = new RecordingMetrics(); + this.finished = new CopyOnWriteArrayList<>(); + this.machine = newMachine(this.view, this.finished::add); + } + + /** + * Checks that a successful connect moves the machine to the running state. + * + *

The connect future must be completed with the client, the listener must be told about the + * opened connection exactly once and the policy must be started exactly once. + */ + @Test + void testConnectSucceedsAndMachineIsRunning() throws Exception { + final CompletableFuture cf = connect(); + + Assertions.assertInstanceOf(RunningState.class, this.machine.state()); + Assertions.assertSame(this.client.client(), cf.get(1, TimeUnit.SECONDS)); + Assertions.assertEquals(1, this.view.listener().connectionOpenedCount()); + Assertions.assertEquals(0, this.view.listener().connectionClosedCount()); + Assertions.assertEquals(1, this.policy.startCalls()); + Assertions.assertEquals(0, this.policy.stopCalls()); + Assertions.assertEquals(1, this.metrics.succeeded.get()); + Assertions.assertEquals(0, this.metrics.failed.get()); + Assertions.assertTrue(this.finished.isEmpty(), "The session must not be finished"); + } + + /** + * Checks that the connect future does not wait for the availability policy. + * + *

A slow policy must not delay the connect: the machine waits in the starting state and the + * client is already handed out. + */ + @Test + void testConnectFutureIsCompletedWithoutWaitingForPolicy() { + final CompletableFuture policyStart = new CompletableFuture<>(); + this.policy.nextStartReturns(policyStart); + + final CompletableFuture cf = connect(); + + Assertions.assertInstanceOf(PolicyStartingState.class, this.machine.state()); + Assertions.assertTrue(cf.isDone(), "The connect future must not wait for the policy"); + Assertions.assertFalse(cf.isCompletedExceptionally()); + + policyStart.complete(null); + + Assertions.assertInstanceOf(RunningState.class, this.machine.state()); + } + + /** Checks that a group without a user is checked with the first ping, not with authorization. */ + @Test + void testConnectWithoutUserSendsFirstPing() { + connect(); + + Assertions.assertEquals(1, this.client.connectCalls()); + Assertions.assertEquals(1, this.client.pingCount()); + Assertions.assertEquals(0, this.client.authorizeCalls()); + Assertions.assertEquals(1, this.client.readyCalls()); + } + + /** Checks that a group with a user is authorized instead of the first ping. */ + @Test + void testConnectWithUserAuthorizes() { + final RecordingPoolEntryView authView = + RecordingPoolEntryView.createWithCredentials( + TAG, IDX, this.policy, this.client.client(), "user", "secret"); + final PoolEntryStateMachine authMachine = newMachine(authView, this.finished::add); + + authMachine.handle(new ConnectEvent(new CompletableFuture<>())); + + Assertions.assertInstanceOf(RunningState.class, authMachine.state()); + Assertions.assertEquals(1, this.client.authorizeCalls()); + Assertions.assertEquals(0, this.client.pingCount()); + Assertions.assertEquals("user", this.client.lastUser()); + Assertions.assertEquals("secret", this.client.lastPassword()); + } + + /** + * Checks the close from the running state. + * + *

The policy must be stopped, the connection must be hidden from the load balancer, the client + * must be closed once and the session must finish as closed by the user. + */ + @Test + void testCloseFromRunningFinishesSessionAsClosedByUser() { + connect(); + final CompletableFuture closeFuture = new CompletableFuture<>(); + + this.machine.handle(new ClientCloseEvent(closeFuture)); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(Arrays.asList("start", "stop"), this.policy.calls()); + Assertions.assertEquals(CONNECTION_LOST_STATE, lastStateName()); + Assertions.assertEquals(1, this.client.closeCalls()); + Assertions.assertEquals(1, this.view.listener().connectionClosedCount()); + Assertions.assertTrue(closeFuture.isDone(), "The close future must be completed"); + Assertions.assertTrue(outcome().isClosedByUser()); + Assertions.assertNull(outcome().cause()); + } + + /** Checks that a failed connect step finishes the session without touching the policy. */ + @Test + void testConnectFailureFinishesSession() { + final TimeoutException cause = new TimeoutException("connect"); + this.client.connectFails(cause); + + final CompletableFuture cf = connect(); + + assertConnectFailed(cf, cause); + } + + /** Checks that a failed authorize/ping step finishes the session. */ + @Test + void testHandshakeFailureFinishesSession() { + final TimeoutException cause = new TimeoutException("first ping"); + this.client.nextPingFails(cause); + + final CompletableFuture cf = connect(); + + assertConnectFailed(cf, cause); + } + + /** Checks that a failed readiness step finishes the session. */ + @Test + void testReadinessFailureFinishesSession() { + final IllegalStateException cause = new IllegalStateException("not ready"); + this.client.readyFails(cause); + + final CompletableFuture cf = connect(); + + assertConnectFailed(cf, cause); + } + + /** Checks that an exception thrown by the client synchronously is handled as a connect error. */ + @Test + void testSynchronousConnectExceptionFinishesSession() { + final IllegalArgumentException cause = new IllegalArgumentException("bad address"); + this.client.connectThrows(cause); + + final CompletableFuture cf = connect(); + + assertConnectFailed(cf, cause); + } + + /** + * Checks that the connect time is measured exactly once per attempt, no matter how it ended. + * + *

A leaked sample of a long task timer shows up as an active task forever. + */ + @Test + void testConnectTimerIsStoppedOnSuccessAndOnFailure() { + connect(); + Assertions.assertEquals(1, this.metrics.started.get()); + Assertions.assertEquals(1, this.metrics.stopped.get()); + + setUp(); + this.client.connectFails(new TimeoutException("connect")); + connect(); + Assertions.assertEquals(1, this.metrics.started.get()); + Assertions.assertEquals(1, this.metrics.stopped.get()); + } + + /** + * Checks that a connection loss during the connect is handled as the connect error exactly once. + * + *

The client may report the close and fail the connect future for the same reason. The control + * event comes first, and the later error of the future must be ignored. + */ + @Test + void testRemoteCloseWhileConnectingCountsOneConnectError() { + final CompletableFuture pending = new CompletableFuture<>(); + this.client.connectReturns(pending); + final CompletableFuture cf = connect(); + Assertions.assertInstanceOf(ConnectingState.class, this.machine.state()); + + final IOException cause = new IOException("reset"); + this.machine.handle(new EntryEvent.RemoteCloseEvent(cause)); + pending.completeExceptionally(cause); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(1, this.metrics.failed.get()); + Assertions.assertSame(cause, outcome().cause()); + Assertions.assertTrue(cf.isCompletedExceptionally()); + } + + /** Checks that a connection loss without a cause during the connect gets a default cause. */ + @Test + void testRemoteCloseWithoutCauseWhileConnectingGetsDefaultCause() { + this.client.connectReturns(new CompletableFuture<>()); + connect(); + + this.machine.handle(new EntryEvent.RemoteCloseEvent(null)); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertInstanceOf(IllegalStateException.class, outcome().cause()); + } + + /** + * Checks that a late success of the connect does not start the policy of a closed session. + * + *

The connect future is completed after the session is finished: nobody must wait for the + * policy any more. + */ + @Test + void testLateConnectSuccessAfterCloseDoesNotStartPolicy() { + final CompletableFuture pending = new CompletableFuture<>(); + this.client.connectReturns(pending); + connect(); + this.machine.handle(new EntryEvent.ReconnectEvent(new IllegalStateException("recycle"))); + + pending.complete(null); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(0, this.policy.startCalls()); + Assertions.assertEquals(0, this.metrics.succeeded.get()); + } + + /** + * Checks that a connection loss is not lost when it races with the success of the connect. + * + *

The loss is sent from the middle of the transition, so the success of the connect is queued + * after it. The control event has the priority: the session must end as a connect error. + */ + @Test + void testControlEventWinsOverQueuedConnectedEvent() { + final IOException cause = new IOException("reset"); + this.client.connectAnswers( + () -> { + this.machine.handle(new EntryEvent.RemoteCloseEvent(cause)); + return CompletableFuture.completedFuture(null); + }); + + final CompletableFuture cf = connect(); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(0, this.metrics.succeeded.get()); + Assertions.assertEquals(1, this.metrics.failed.get()); + Assertions.assertEquals(0, this.policy.startCalls()); + Assertions.assertTrue(cf.isCompletedExceptionally()); + Assertions.assertSame(cause, outcome().cause()); + } + + /** + * Checks that a failed start of the policy stops the policy and restarts it. + * + *

The connection stays open and the order of the calls is strict: start, stop, start. The stop + * receives the cause of the failed start. + */ + @Test + void testFailedPolicyStartIsRecycledWithStopAndStart() { + final IllegalStateException cause = new IllegalStateException("start failed"); + this.policy.nextStartFails(cause); + + connect(); + + Assertions.assertInstanceOf(PolicyRestartingState.class, this.machine.state()); + Assertions.assertEquals(Arrays.asList("start", "stop"), this.policy.calls()); + Assertions.assertSame(cause, this.policy.stopCauses().get(0)); + Assertions.assertEquals(1, this.policy.backoffCalls()); + Assertions.assertEquals(1, this.timer.pendingCount(), "The restart must wait for the timer"); + + this.timer.fireNext(); + + Assertions.assertInstanceOf(RunningState.class, this.machine.state()); + Assertions.assertEquals(Arrays.asList("start", "stop", "start"), this.policy.calls()); + Assertions.assertEquals(0, this.client.closeCalls(), "The client must stay open"); + Assertions.assertTrue(this.finished.isEmpty()); + } + + /** Checks that an exception thrown by {@code start} synchronously is handled like a failure. */ + @Test + void testSynchronousPolicyStartExceptionIsRecycled() { + this.policy.nextStartThrows(new IllegalStateException("start threw")); + + connect(); + + Assertions.assertInstanceOf(PolicyRestartingState.class, this.machine.state()); + Assertions.assertEquals(1, this.policy.stopCalls()); + } + + /** Checks that the restart waits for the backoff given by the policy. */ + @Test + void testRestartWaitsForPolicyBackoff() { + this.policy.backoff(Duration.ofSeconds(5)).nextStartFails(new IllegalStateException("x")); + + connect(); + + Assertions.assertEquals(1, this.policy.startCalls(), "The policy must not restart at once"); + Assertions.assertEquals(5_000, this.timer.lastScheduled().delayMillis()); + + this.timer.fireNext(); + + Assertions.assertEquals(2, this.policy.startCalls()); + } + + /** Checks that an absent or failing backoff is replaced with zero. */ + @Test + void testNullAndFailingBackoffAreReplacedWithZero() { + this.policy.backoff(null).nextStartFails(new IllegalStateException("x")); + connect(); + Assertions.assertInstanceOf(PolicyRestartingState.class, this.machine.state()); + Assertions.assertEquals(0, this.timer.lastScheduled().delayMillis()); + + setUp(); + this.policy.backoffThrows(new IllegalStateException("backoff")); + this.policy.nextStartFails(new IllegalStateException("x")); + connect(); + Assertions.assertInstanceOf(PolicyRestartingState.class, this.machine.state()); + Assertions.assertEquals(0, this.timer.lastScheduled().delayMillis()); + } + + /** Checks that a failed stop does not break the close. */ + @Test + void testFailedPolicyStopDoesNotBreakClose() { + connect(); + this.policy.nextStopFails(new IllegalStateException("stop failed")); + + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(1, this.client.closeCalls()); + } + + /** Checks that a stop that throws synchronously does not break the close. */ + @Test + void testSynchronousPolicyStopExceptionDoesNotBreakClose() { + connect(); + this.policy.nextStopThrows(new IllegalStateException("stop threw")); + + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(1, this.client.closeCalls()); + } + + /** Checks that a failed stop of a failed start does not break the restart. */ + @Test + void testFailedStopDuringRestartStillRestarts() { + this.policy.nextStartFails(new IllegalStateException("start")); + this.policy.nextStopFails(new IllegalStateException("stop")); + + connect(); + + Assertions.assertInstanceOf(PolicyRestartingState.class, this.machine.state()); + this.timer.fireNext(); + Assertions.assertInstanceOf(RunningState.class, this.machine.state()); + } + + /** Checks that the policy is never stopped if it has never been started. */ + @Test + void testPolicyIsNotStoppedIfItWasNotStarted() { + this.client.connectFails(new TimeoutException("connect")); + + connect(); + + Assertions.assertEquals(0, this.policy.startCalls()); + Assertions.assertEquals(0, this.policy.stopCalls()); + } + + /** + * Checks that the policy is stopped exactly once, however many reasons come while it stops. + * + *

The stop is slow. Several reasons to finish the session come during it: they must be + * remembered, and the stop must not be called again. + */ + @Test + void testPolicyIsStoppedOnceWhileStopIsInFlight() { + connect(); + final CompletableFuture policyStop = new CompletableFuture<>(); + this.policy.nextStopReturns(policyStop); + + this.machine.handle(new EntryEvent.ReconnectEvent(new IllegalStateException("first"))); + this.machine.handle(new EntryEvent.ReconnectEvent(new IllegalStateException("second"))); + this.machine.handle(new EntryEvent.RemoteCloseEvent(new IOException("third"))); + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + + Assertions.assertInstanceOf(PolicyStoppingState.class, this.machine.state()); + Assertions.assertEquals(1, this.policy.stopCalls()); + + policyStop.complete(null); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(1, this.policy.stopCalls()); + Assertions.assertEquals(1, this.client.closeCalls()); + } + + /** Checks that a late result of the start is ignored once the session is being finished. */ + @Test + void testLatePolicyStartResultIsIgnoredWhileStopping() { + final CompletableFuture policyStart = new CompletableFuture<>(); + this.policy.nextStartReturns(policyStart); + final CompletableFuture policyStop = new CompletableFuture<>(); + this.policy.nextStopReturns(policyStop); + connect(); + Assertions.assertInstanceOf(PolicyStartingState.class, this.machine.state()); + + this.machine.handle(new EntryEvent.ReconnectEvent(new IllegalStateException("recycle"))); + Assertions.assertInstanceOf(PolicyStoppingState.class, this.machine.state()); + policyStart.complete(null); + + Assertions.assertInstanceOf( + PolicyStoppingState.class, + this.machine.state(), + "A late start must not bring the machine to the running state"); + + policyStop.complete(null); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + } + + /** Checks that the close during the stop that follows a failed start prevents the restart. */ + @Test + void testCloseDuringStopAfterFailedStartPreventsRestart() { + this.policy.nextStartFails(new IllegalStateException("start")); + final CompletableFuture policyStop = new CompletableFuture<>(); + this.policy.nextStopReturns(policyStop); + connect(); + Assertions.assertInstanceOf(PolicyStoppingState.class, this.machine.state()); + + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + policyStop.complete(null); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(0, this.policy.backoffCalls(), "The policy must not be restarted"); + Assertions.assertEquals(1, this.policy.startCalls()); + Assertions.assertTrue(outcome().isClosedByUser()); + } + + /** Checks that the close while the restart waits for the backoff cancels the timer. */ + @Test + void testCloseWhileWaitingForBackoffCancelsTimer() { + this.policy.backoff(Duration.ofSeconds(5)).nextStartFails(new IllegalStateException("x")); + connect(); + final FakeTimeout backoff = this.timer.lastScheduled(); + Assertions.assertInstanceOf(PolicyRestartingState.class, this.machine.state()); + + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertTrue(backoff.isCancelled(), "The backoff timer must be cancelled"); + Assertions.assertEquals(1, this.policy.startCalls()); + } + + /** Checks that a backoff that fires after the close is ignored. */ + @Test + void testStaleBackoffAfterCloseIsIgnored() { + this.policy.backoff(Duration.ofSeconds(5)).nextStartFails(new IllegalStateException("x")); + connect(); + final FakeTimeout backoff = this.timer.lastScheduled(); + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + + backoff.fire(); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(1, this.policy.startCalls()); + } + + /** Checks that a close of a fresh machine finishes it at once and touches nothing. */ + @Test + void testCloseInInitStateFinishesImmediately() { + final CompletableFuture closeFuture = new CompletableFuture<>(); + + this.machine.handle(new ClientCloseEvent(closeFuture)); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertTrue(closeFuture.isDone()); + Assertions.assertEquals(0, this.client.connectCalls()); + Assertions.assertEquals(0, this.policy.startCalls()); + Assertions.assertEquals(0, this.policy.stopCalls()); + Assertions.assertTrue(outcome().isClosedByUser()); + } + + /** Checks that a connection loss and a reconnect request are meaningless before the connect. */ + @Test + void testRemoteCloseAndReconnectInInitStateAreIgnored() { + this.machine.handle(new EntryEvent.RemoteCloseEvent(new IOException("x"))); + this.machine.handle(new EntryEvent.ReconnectEvent(new IOException("y"))); + + Assertions.assertInstanceOf(InitState.class, this.machine.state()); + Assertions.assertTrue(this.finished.isEmpty()); + } + + /** Checks that a connect request after the close fails the connect future. */ + @Test + void testConnectAfterCloseFailsWithPoolClosedException() { + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + final CompletableFuture cf = new CompletableFuture<>(); + + this.machine.handle(new ConnectEvent(cf)); + + Assertions.assertTrue(cf.isCompletedExceptionally()); + final ExecutionException e = Assertions.assertThrows(ExecutionException.class, cf::get); + Assertions.assertInstanceOf(PoolClosedException.class, e.getCause()); + Assertions.assertEquals(0, this.client.connectCalls()); + } + + /** Checks the close while connecting: the policy must not be touched. */ + @Test + void testCloseWhileConnectingFinishesAsClosedByUser() { + this.client.connectReturns(new CompletableFuture<>()); + connect(); + + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertTrue(outcome().isClosedByUser()); + Assertions.assertEquals(0, this.policy.startCalls()); + Assertions.assertEquals(1, this.client.closeCalls()); + } + + /** Checks that a reconnect request while connecting recycles the session with its cause. */ + @Test + void testReconnectWhileConnectingFinishesAsFailed() { + this.client.connectReturns(new CompletableFuture<>()); + connect(); + final IllegalStateException cause = new IllegalStateException("recycle"); + + this.machine.handle(new EntryEvent.ReconnectEvent(cause)); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertFalse(outcome().isClosedByUser()); + Assertions.assertSame(cause, outcome().cause()); + } + + /** Checks that a connection loss from the running state finishes the session as failed. */ + @Test + void testRemoteCloseWhileRunningFinishesAsFailed() { + connect(); + final IOException cause = new IOException("reset"); + + this.machine.handle(new EntryEvent.RemoteCloseEvent(cause)); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertSame(cause, outcome().cause()); + Assertions.assertEquals(Arrays.asList("start", "stop"), this.policy.calls()); + Assertions.assertSame(cause, this.policy.stopCauses().get(0)); + Assertions.assertEquals(CONNECTION_LOST_STATE, lastStateName()); + } + + /** Checks that a reconnect without a cause finishes the session as failed with no cause. */ + @Test + void testReconnectWithoutCauseFinishesAsFailedWithoutCause() { + connect(); + + this.machine.handle(new EntryEvent.ReconnectEvent(null)); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertFalse(outcome().isClosedByUser()); + Assertions.assertNull(outcome().cause()); + } + + /** Checks that the first reason of the finish wins when the policy is being stopped. */ + @Test + void testFirstReasonWinsReconnectThenClose() { + connect(); + final CompletableFuture policyStop = new CompletableFuture<>(); + this.policy.nextStopReturns(policyStop); + final IllegalStateException first = new IllegalStateException("first"); + final CompletableFuture closeFuture = new CompletableFuture<>(); + + this.machine.handle(new EntryEvent.ReconnectEvent(first)); + this.machine.handle(new ClientCloseEvent(closeFuture)); + policyStop.complete(null); + + Assertions.assertSame(first, outcome().cause()); + Assertions.assertFalse(outcome().isClosedByUser()); + Assertions.assertTrue(closeFuture.isDone(), "The close future must still be completed"); + } + + /** Checks that the first reason wins in the opposite order: the close, then the reconnect. */ + @Test + void testFirstReasonWinsCloseThenReconnect() { + connect(); + final CompletableFuture policyStop = new CompletableFuture<>(); + this.policy.nextStopReturns(policyStop); + + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + this.machine.handle(new EntryEvent.ReconnectEvent(new IllegalStateException("late"))); + policyStop.complete(null); + + Assertions.assertTrue(outcome().isClosedByUser()); + Assertions.assertNull(outcome().cause()); + } + + /** Checks that repeated closes of a closed machine only complete their futures. */ + @Test + void testRepeatedCloseOfClosedMachineCompletesFutures() { + connect(); + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + final CompletableFuture again = new CompletableFuture<>(); + + this.machine.handle(new ClientCloseEvent(again)); + this.machine.handle(new EntryEvent.RemoteCloseEvent(new IOException("stale"))); + this.machine.handle(new EntryEvent.ReconnectEvent(new IOException("stale"))); + + Assertions.assertTrue(again.isDone()); + Assertions.assertEquals(1, this.finished.size(), "The session must be finished once"); + Assertions.assertEquals(1, this.client.closeCalls(), "The client must be closed once"); + Assertions.assertEquals(1, this.view.listener().connectionClosedCount()); + } + + /** Checks that a client that cannot be closed does not stop the machine in the closing state. */ + @Test + void testClientCloseFailureStillFinishesSession() { + connect(); + this.client.closeThrows(new IOException("close failed")); + + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(1, this.client.closeCalls()); + Assertions.assertEquals(1, this.finished.size()); + } + + /** Checks that a failing finish callback does not break the machine. */ + @Test + void testFailingFinishCallbackIsSwallowed() { + final PoolEntryStateMachine failing = + newMachine( + this.view, + o -> { + throw new IllegalStateException("callback failed"); + }); + + Assertions.assertDoesNotThrow( + () -> failing.handle(new ClientCloseEvent(new CompletableFuture<>()))); + + Assertions.assertInstanceOf(ClosedState.class, failing.state()); + } + + /** + * Checks that concurrent reasons to finish the session end it exactly once. + * + *

Many threads recycle, close and report a connection loss at the same time. The session must + * be finished once, the client must be closed once and the policy must be stopped once. + */ + @Test + void testConcurrentFinishReasonsFinishSessionOnce() throws Exception { + connect(); + final int threads = 16; + final ExecutorService pool = Executors.newFixedThreadPool(threads); + final CountDownLatch start = new CountDownLatch(1); + final List> closeFutures = new ArrayList<>(); + try { + final List> tasks = new ArrayList<>(); + for (int i = 0; i < threads; i++) { + final int n = i; + final CompletableFuture closeFuture = new CompletableFuture<>(); + closeFutures.add(closeFuture); + tasks.add( + CompletableFuture.runAsync( + () -> { + await(start); + switch (n % 3) { + case 0: + this.machine.handle(new ClientCloseEvent(closeFuture)); + break; + case 1: + this.machine.handle(new EntryEvent.ReconnectEvent(new IOException("r"))); + break; + default: + this.machine.handle(new EntryEvent.RemoteCloseEvent(new IOException("c"))); + } + }, + pool)); + } + start.countDown(); + CompletableFuture.allOf(tasks.toArray(new CompletableFuture[0])).get(5, TimeUnit.SECONDS); + } finally { + pool.shutdownNow(); + } + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertEquals(1, this.finished.size()); + Assertions.assertEquals(1, this.client.closeCalls()); + Assertions.assertEquals(1, this.policy.stopCalls()); + Assertions.assertEquals(1, this.view.listener().connectionClosedCount()); + for (int i = 0; i < threads; i += 3) { + Assertions.assertTrue(closeFutures.get(i).isDone(), "The close future must be completed"); + } + } + + /** + * Checks that an exception thrown by a state handler recycles the session instead of breaking it. + * + *

The metrics fail on the successful connect, so the handler of the connected event throws. + * The machine must treat it as a reason to recycle the session: it finishes with the exception as + * the cause, the policy is not started, the client is closed and the connect future fails. + */ + @Test + void testExceptionInHandlerRecyclesSessionWithItAsCause() { + final IllegalStateException failure = new IllegalStateException("metrics failed"); + this.metrics.succeededFailure = failure; + + final CompletableFuture cf = connect(); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertSame(failure, outcome().cause()); + Assertions.assertFalse(outcome().isClosedByUser()); + Assertions.assertTrue(cf.isCompletedExceptionally(), "The connect future must fail"); + Assertions.assertEquals(0, this.policy.startCalls()); + Assertions.assertEquals(1, this.client.closeCalls()); + Assertions.assertEquals(1, this.view.listener().connectionClosedCount()); + } + + /** Checks that an exception from the view while the connect is reported recycles the session. */ + @Test + void testExceptionFromViewEmitWhileConnectedRecyclesSession() { + final IllegalStateException failure = new IllegalStateException("emit failed"); + this.view.failEmitOnCall(1, failure); + + final CompletableFuture cf = connect(); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertSame(failure, outcome().cause()); + Assertions.assertTrue(cf.isCompletedExceptionally()); + Assertions.assertEquals(0, this.policy.startCalls()); + Assertions.assertEquals(1, this.client.closeCalls()); + } + + /** + * Checks that an exception thrown by the entry action of a state recycles the session. + * + *

The view fails to give the client, so the connecting state throws before it uses the client. + * The closing state must survive the same failure: it cannot close a client it cannot get. + */ + @Test + void testExceptionInEntryActionRecyclesSession() { + final IllegalStateException failure = new IllegalStateException("no client"); + this.view.failClient(failure); + + final CompletableFuture cf = connect(); + + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertSame(failure, outcome().cause()); + Assertions.assertTrue(cf.isCompletedExceptionally()); + Assertions.assertEquals(0, this.client.connectCalls()); + Assertions.assertEquals(0, this.policy.startCalls()); + } + + /** + * Checks that a timer that cannot schedule the policy restart recycles the session. + * + *

The policy start fails, so the machine must schedule the restart, but the timer throws. The + * session must not hang in the restarting state: it finishes with the exception of the timer as + * the cause, the policy has been stopped once and the client is closed. + */ + @Test + void testTimerFailureWhileSchedulingRestartRecyclesSession() { + this.policy.nextStartFails(new IllegalStateException("start failed")); + final PoolEntryStateMachine brokenTimerMachine = + newMachine(this.view, new FlakyTimer(this.timer, 1), this.finished::add); + + final CompletableFuture cf = connect(brokenTimerMachine); + + Assertions.assertInstanceOf(ClosedState.class, brokenTimerMachine.state()); + Assertions.assertEquals("the timer is broken", outcome().cause().getMessage()); + Assertions.assertEquals(Arrays.asList("start", "stop"), this.policy.calls()); + Assertions.assertEquals(1, this.client.closeCalls()); + Assertions.assertEquals(CONNECTION_LOST_STATE, lastStateName()); + Assertions.assertFalse(cf.isCompletedExceptionally(), "The client had been connected"); + Assertions.assertEquals(0, this.timer.pendingCount(), "No restart must be left pending"); + } + + /** + * Checks that a view that fails to hide the connection does not leave the session in the closing + * state. + * + *

The closing state hides the connection first. If it throws, the client must still be closed + * and the session must still be finished: otherwise the entry never reconnects and a close waits + * forever. + */ + @Test + void testChangeStateFailureInClosingStillFinishesSession() { + this.view.failChangeStateWhen( + s -> CONNECTION_LOST_STATE.equals(s.name()), + new IllegalStateException("changeState failed")); + connect(); + final CompletableFuture closeFuture = new CompletableFuture<>(); + + this.machine.handle(new ClientCloseEvent(closeFuture)); + + Assertions.assertInstanceOf( + ClosedState.class, this.machine.state(), "The session must not hang in CLOSING"); + Assertions.assertEquals(1, this.finished.size()); + Assertions.assertEquals(1, this.client.closeCalls()); + Assertions.assertTrue(closeFuture.isDone(), "The close future must be completed"); + } + + /** + * Checks that a failing notification of the listener does not prevent the session from finishing. + * + *

The final state notifies the listener first. If it throws, the futures must still be + * completed and the finish callback must still be called: the entry relies on it to reconnect. + */ + @Test + void testEmitFailureInClosedStillFinishesSession() { + this.view.failEmitOnCall(2, new IllegalStateException("emit")); + connect(); + final CompletableFuture closeFuture = new CompletableFuture<>(); + + this.machine.handle(new ClientCloseEvent(closeFuture)); + + Assertions.assertEquals(1, this.finished.size(), "The finish callback must be called"); + Assertions.assertTrue(closeFuture.isDone(), "The close future must be completed"); + Assertions.assertTrue(outcome().isClosedByUser()); + } + + /** Checks that the address, the timeout and the graceful shutdown flag reach the client. */ + @Test + void testConnectPassesAddressTimeoutAndGracefulShutdownToClient() { + final PoolEntryStateMachine custom = + new PoolEntryStateMachine( + this.view, + this.policy, + this.timer, + 2_500L, + false, + ConnectionMetrics.NOOP, + this.finished::add); + + custom.handle(new ConnectEvent(new CompletableFuture<>())); + + Mockito.verify(this.client.client()) + .connect(this.view.metadata().settings().getAddress(), 2_500L, false); + } + + /** Checks that the first check of a connection without a user is the short ping. */ + @Test + void testFirstPingUsesFirstPingOptions() { + connect(); + + Mockito.verify(this.client.client()).ping(PoolEntryStateMachine.FIRST_PING_OPTS); + } + + /** Checks that the authorization gets the user, the password and the auth type of the group. */ + @Test + void testAuthorizePassesCredentialsAndAuthType() { + final RecordingPoolEntryView authView = + RecordingPoolEntryView.createWithCredentials( + TAG, IDX, this.policy, this.client.client(), "user", "secret"); + final PoolEntryStateMachine authMachine = newMachine(authView, this.finished::add); + + authMachine.handle(new ConnectEvent(new CompletableFuture<>())); + + Mockito.verify(this.client.client()) + .authorize("user", "secret", authView.metadata().settings().getAuthType()); + } + + /** + * Checks that a machine works without metrics. + * + *

The metrics are optional: a missing one must be replaced with a stub that does nothing. + */ + @Test + void testMachineWorksWithoutMetrics() { + final PoolEntryStateMachine noMetrics = + new PoolEntryStateMachine( + this.view, this.policy, this.timer, 1_000L, true, null, this.finished::add); + + noMetrics.handle(new ConnectEvent(new CompletableFuture<>())); + + Assertions.assertInstanceOf(RunningState.class, noMetrics.state()); + } + + /** Checks that every required argument of the constructor is checked. */ + @Test + void testConstructorRejectsNullArguments() { + final Consumer callback = this.finished::add; + + Assertions.assertThrows( + NullPointerException.class, + () -> + new PoolEntryStateMachine( + null, this.policy, this.timer, 1_000L, true, this.metrics, callback)); + Assertions.assertThrows( + NullPointerException.class, + () -> + new PoolEntryStateMachine( + this.view, null, this.timer, 1_000L, true, this.metrics, callback)); + Assertions.assertThrows( + NullPointerException.class, + () -> + new PoolEntryStateMachine( + this.view, this.policy, null, 1_000L, true, this.metrics, callback)); + Assertions.assertThrows( + NullPointerException.class, + () -> + new PoolEntryStateMachine( + this.view, this.policy, this.timer, 1_000L, true, this.metrics, null)); + } + + /** Checks that a null event is ignored. */ + @Test + void testNullEventIsIgnored() { + connect(); + + Assertions.assertDoesNotThrow(() -> this.machine.handle(null)); + + Assertions.assertInstanceOf(RunningState.class, this.machine.state()); + } + + /** Checks that the policy is stopped without a cause when the entry is closed on purpose. */ + @Test + void testPolicyStopGetsNoCauseWhenClosedByUser() { + connect(); + + this.machine.handle(new ClientCloseEvent(new CompletableFuture<>())); + + Assertions.assertEquals(1, this.policy.stopCauses().size()); + Assertions.assertNull(this.policy.stopCauses().get(0)); + } + + /** Checks that the policy gets the cause of the reconnect request. */ + @Test + void testPolicyStopGetsCauseOfReconnect() { + connect(); + final IllegalStateException cause = new IllegalStateException("recycle"); + + this.machine.handle(new EntryEvent.ReconnectEvent(cause)); + + Assertions.assertSame(cause, this.policy.stopCauses().get(0)); + } + + /** + * Checks that a cause wrapped by the futures is unwrapped. + * + *

The client reports errors wrapped into {@code CompletionException}: the listeners and the + * policy must see the original one. + */ + @Test + void testWrappedCausesAreUnwrapped() { + connect(); + final IOException cause = new IOException("reset"); + + this.machine.handle(new EntryEvent.RemoteCloseEvent(new CompletionException(cause))); + + Assertions.assertSame(cause, outcome().cause()); + Assertions.assertSame(cause, this.policy.stopCauses().get(0)); + } + + /** Checks that a connect failure wrapped by the futures is unwrapped. */ + @Test + void testWrappedConnectFailureIsUnwrapped() { + final TimeoutException cause = new TimeoutException("connect"); + this.client.connectFails(new CompletionException(cause)); + + connect(); + + Assertions.assertSame(cause, outcome().cause()); + } + + /** + * Checks several restart cycles in a row. + * + *

The policy start fails twice and then succeeds: each failure is followed by a stop with its + * own cause and by a new backoff. + */ + @Test + void testPolicyIsRestartedSeveralTimes() { + final IllegalStateException first = new IllegalStateException("first"); + final IllegalStateException second = new IllegalStateException("second"); + this.policy.nextStartFails(first).nextStartFails(second); + + connect(); + this.timer.fireNext(); + + Assertions.assertInstanceOf(PolicyRestartingState.class, this.machine.state()); + this.timer.fireNext(); + + Assertions.assertInstanceOf(RunningState.class, this.machine.state()); + Assertions.assertEquals( + Arrays.asList("start", "stop", "start", "stop", "start"), this.policy.calls()); + Assertions.assertEquals(Arrays.asList(first, second), this.policy.stopCauses()); + Assertions.assertEquals(2, this.policy.backoffCalls()); + } + + private CompletableFuture connect(PoolEntryStateMachine target) { + final CompletableFuture cf = new CompletableFuture<>(); + target.handle(new ConnectEvent(cf)); + return cf; + } + + private PoolEntryStateMachine newMachine(PoolEntryView entryView, Consumer onFinished) { + return newMachine(entryView, this.timer, onFinished); + } + + private PoolEntryStateMachine newMachine( + PoolEntryView entryView, Timer machineTimer, Consumer onFinished) { + return new PoolEntryStateMachine( + entryView, this.policy, machineTimer, 1_000L, true, this.metrics, onFinished); + } + + private CompletableFuture connect() { + final CompletableFuture cf = new CompletableFuture<>(); + this.machine.handle(new ConnectEvent(cf)); + return cf; + } + + private Outcome outcome() { + Assertions.assertEquals(1, this.finished.size(), "The session must be finished exactly once"); + return this.finished.get(0); + } + + private String lastStateName() { + final List names = this.view.stateChangeNames(); + return names.isEmpty() ? null : names.get(names.size() - 1); + } + + private void assertConnectFailed(CompletableFuture cf, Throwable cause) { + Assertions.assertInstanceOf(ClosedState.class, this.machine.state()); + Assertions.assertTrue(cf.isCompletedExceptionally(), "The connect future must fail"); + final ExecutionException e = Assertions.assertThrows(ExecutionException.class, cf::get); + Assertions.assertSame(cause, e.getCause()); + Assertions.assertSame(cause, outcome().cause()); + Assertions.assertFalse(outcome().isClosedByUser()); + Assertions.assertEquals(1, this.metrics.failed.get()); + Assertions.assertEquals(0, this.metrics.succeeded.get()); + Assertions.assertEquals(0, this.policy.startCalls()); + Assertions.assertEquals(0, this.policy.stopCalls()); + Assertions.assertEquals(1, this.client.closeCalls()); + Assertions.assertEquals(1, this.view.listener().connectionClosedCount()); + Assertions.assertEquals(0, this.view.listener().connectionOpenedCount()); + Assertions.assertEquals(CONNECTION_LOST_STATE, lastStateName()); + } + + private static void await(CountDownLatch latch) { + try { + latch.await(); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(e); + } + } + + /** Counts the metric calls of the machine. */ + private static final class RecordingMetrics implements ConnectionMetrics { + + final AtomicInteger started = new AtomicInteger(); + final AtomicInteger stopped = new AtomicInteger(); + final AtomicInteger succeeded = new AtomicInteger(); + final AtomicInteger failed = new AtomicInteger(); + volatile RuntimeException succeededFailure; + + @Override + public LongTaskTimer.Sample startConnectTimer() { + this.started.incrementAndGet(); + return null; + } + + @Override + public void stopConnectTimer(LongTaskTimer.Sample sample) { + this.stopped.incrementAndGet(); + } + + @Override + public void connectSucceeded() { + this.succeeded.incrementAndGet(); + final RuntimeException failure = this.succeededFailure; + if (failure != null) { + throw failure; + } + } + + @Override + public void connectFailed(Throwable cause) { + this.failed.incrementAndGet(); + } + } +} diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/RecordingPoolEntryView.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/RecordingPoolEntryView.java index d0afaa45..7c2b41cd 100644 --- a/tarantool-pooling/src/test/java/io/tarantool/pool/support/RecordingPoolEntryView.java +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/RecordingPoolEntryView.java @@ -11,6 +11,7 @@ import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; +import java.util.function.Predicate; import io.tarantool.core.IProtoClient; import io.tarantool.pool.HeartbeatEvent; @@ -55,6 +56,12 @@ public final class RecordingPoolEntryView implements PoolEntryView { private final AtomicInteger clientCalls = new AtomicInteger(); private final AtomicInteger nullStateChanges = new AtomicInteger(); private final AtomicInteger nullEmitCalls = new AtomicInteger(); + private final AtomicInteger emitCalls = new AtomicInteger(); + private volatile Predicate changeStateFailFilter = s -> false; + private volatile RuntimeException changeStateFailure; + private volatile int emitFailureCall = -1; + private volatile RuntimeException emitFailure; + private volatile RuntimeException clientFailure; private volatile PoolEntryState state = CLOSED_STATE; private RecordingPoolEntryView(Metadata metadata, IProtoClient client) { @@ -73,19 +80,43 @@ private RecordingPoolEntryView(Metadata metadata, IProtoClient client) { */ public static RecordingPoolEntryView create( String tag, int index, AvailabilityPolicy policy, IProtoClient client) { - return new RecordingPoolEntryView(newMetadata(tag, index, policy), client); + return new RecordingPoolEntryView(newMetadata(tag, index, policy, null, null), client); } - private static Metadata newMetadata(String tag, int index, AvailabilityPolicy policy) { - final InstanceConnectionGroup group = + /** + * Creates a view for a connection of a group that requires authorization. + * + * @param tag the tag of the connection group + * @param index the index of the connection within the group + * @param policy the policy under test, exposed through the group settings + * @param client the client of the connection + * @param user the user of the group + * @param password the password of the group + * @return the view instance + */ + public static RecordingPoolEntryView createWithCredentials( + String tag, + int index, + AvailabilityPolicy policy, + IProtoClient client, + String user, + String password) { + return new RecordingPoolEntryView(newMetadata(tag, index, policy, user, password), client); + } + + private static Metadata newMetadata( + String tag, int index, AvailabilityPolicy policy, String user, String password) { + final InstanceConnectionGroup.Builder builder = InstanceConnectionGroup.builder() .withHost(InstanceConnectionGroup.DEFAULT_HOST) .withPort(InstanceConnectionGroup.DEFAULT_PORT) .withSize(1) .withTag(tag) - .withAvailabilityPolicy(policy) - .build(); - return new Metadata(group, index) {}; + .withAvailabilityPolicy(policy); + if (user != null) { + builder.withUser(user).withPassword(password); + } + return new Metadata(builder.build(), index) {}; } @Override @@ -94,11 +125,55 @@ public void changeState(PoolEntryState newState) { this.nullStateChanges.incrementAndGet(); throw new NullPointerException("The connection state must not be null"); } + final RuntimeException failure = this.changeStateFailure; + if (failure != null && this.changeStateFailFilter.test(newState)) { + throw failure; + } this.stateChanges.add(newState); this.calls.add("changeState:" + newState.name()); this.state = newState; } + /** + * Makes {@link #changeState(PoolEntryState)} throw for the states accepted by the filter. The + * failed call is not recorded. It lets the test check how a caller survives a failing view. + * + * @param filter selects the states that fail + * @param failure the exception to throw + * @return this view + */ + public RecordingPoolEntryView failChangeStateWhen( + Predicate filter, RuntimeException failure) { + this.changeStateFailFilter = filter; + this.changeStateFailure = failure; + return this; + } + + /** + * Makes the {@link #emit(Consumer)} call with the given number throw. The failed call is not + * recorded. + * + * @param call the number of the call, starting from 1 + * @param failure the exception to throw + * @return this view + */ + public RecordingPoolEntryView failEmitOnCall(int call, RuntimeException failure) { + this.emitFailureCall = call; + this.emitFailure = failure; + return this; + } + + /** + * Makes {@link #client()} always throw. + * + * @param failure the exception to throw + * @return this view + */ + public RecordingPoolEntryView failClient(RuntimeException failure) { + this.clientFailure = failure; + return this; + } + @Override public Metadata metadata() { return this.metadata; @@ -119,6 +194,10 @@ public PoolEntryState state() { @Override public IProtoClient client() { + final RuntimeException failure = this.clientFailure; + if (failure != null) { + throw failure; + } this.clientCalls.incrementAndGet(); this.calls.add("client"); return this.client; @@ -136,6 +215,11 @@ public void emit(Consumer action) { this.nullEmitCalls.incrementAndGet(); throw new NullPointerException("The action must not be null"); } + final int call = this.emitCalls.incrementAndGet(); + final RuntimeException failure = this.emitFailure; + if (failure != null && call == this.emitFailureCall) { + throw failure; + } this.calls.add("emit"); action.accept(this.listener); } 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 new file mode 100644 index 00000000..caf67c51 --- /dev/null +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/ScriptedPolicy.java @@ -0,0 +1,170 @@ +/* + * Copyright (c) 2026 VK DIGITAL TECHNOLOGIES LIMITED LIABILITY COMPANY + * All Rights Reserved. + */ + +package io.tarantool.pool.support; + +import java.time.Duration; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Supplier; + +import io.micrometer.core.instrument.MeterRegistry; +import io.netty.util.Timer; + +import io.tarantool.pool.PoolEntryState; +import io.tarantool.pool.PoolEntryView; +import io.tarantool.pool.availability.AvailabilityPolicy; + +/** + * An {@link AvailabilityPolicy} whose answers are scripted by the test. + * + *

{@code start} and {@code stop} take their answers from the queues in the order of the + * scripting. When a queue is empty, the call succeeds immediately. The test may make a call fail, + * throw or hang, or take over the future and complete it at a chosen moment. + * + *

The policy records the order of the lifecycle calls ({@code start}, {@code stop}), so the test + * may check that {@code stop} is never called before {@code start} and is called once per start. + * The policy never changes the state of the view by itself. + */ +public final class ScriptedPolicy implements AvailabilityPolicy { + + /** The state returned by {@link #initState(PoolEntryView)}. */ + public static final PoolEntryState INITIAL_STATE = new PoolEntryState("INITIAL", false) {}; + + private final Queue>> startOutcomes = + new ConcurrentLinkedQueue<>(); + private final Queue>> stopOutcomes = + new ConcurrentLinkedQueue<>(); + private final List calls = new CopyOnWriteArrayList<>(); + private final List stopCauses = 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; + + /** The next {@code start} fails asynchronously with the given cause. */ + public ScriptedPolicy nextStartFails(Throwable cause) { + this.startOutcomes.add(() -> failed(cause)); + return this; + } + + /** The next {@code start} throws synchronously. */ + public ScriptedPolicy nextStartThrows(RuntimeException exception) { + this.startOutcomes.add( + () -> { + throw exception; + }); + return this; + } + + /** The next {@code start} returns the given future: the test completes it. */ + public ScriptedPolicy nextStartReturns(CompletableFuture future) { + this.startOutcomes.add(() -> future); + return this; + } + + /** The next {@code stop} fails asynchronously with the given cause. */ + public ScriptedPolicy nextStopFails(Throwable cause) { + this.stopOutcomes.add(() -> failed(cause)); + return this; + } + + /** The next {@code stop} throws synchronously. */ + public ScriptedPolicy nextStopThrows(RuntimeException exception) { + this.stopOutcomes.add( + () -> { + throw exception; + }); + return this; + } + + /** The next {@code stop} returns the given future: the test completes it. */ + public ScriptedPolicy nextStopReturns(CompletableFuture future) { + this.stopOutcomes.add(() -> future); + return this; + } + + /** {@code restartBackoff} returns the given duration (may be null). */ + public ScriptedPolicy backoff(Duration duration) { + this.backoff = () -> duration; + return this; + } + + /** {@code restartBackoff} throws the given exception. */ + public ScriptedPolicy backoffThrows(RuntimeException exception) { + this.backoff = + () -> { + throw exception; + }; + return this; + } + + /** The recorded lifecycle calls in the order of their occurrence: {@code start}, {@code stop}. */ + public List calls() { + return this.calls; + } + + /** The causes passed to {@code stop}, in the order of the calls. May contain nulls. */ + public List stopCauses() { + return this.stopCauses; + } + + public int startCalls() { + return this.startCalls.get(); + } + + public int stopCalls() { + return this.stopCalls.get(); + } + + public int backoffCalls() { + return this.backoffCalls.get(); + } + + @Override + public void configure(Timer timer, MeterRegistry metrics) {} + + @Override + public PoolEntryState initState(PoolEntryView view) { + return INITIAL_STATE; + } + + @Override + public Duration restartBackoff(PoolEntryView view) { + this.backoffCalls.incrementAndGet(); + return this.backoff.get(); + } + + @Override + public CompletionStage start(PoolEntryView view) { + this.startCalls.incrementAndGet(); + this.calls.add("start"); + return next(this.startOutcomes); + } + + @Override + public CompletionStage stop(PoolEntryView view, Throwable cause) { + this.stopCalls.incrementAndGet(); + this.calls.add("stop"); + this.stopCauses.add(cause); + return next(this.stopOutcomes); + } + + private static CompletableFuture next(Queue>> outcomes) { + final Supplier> outcome = outcomes.poll(); + return outcome == null ? CompletableFuture.completedFuture(null) : outcome.get(); + } + + private static CompletableFuture failed(Throwable cause) { + final CompletableFuture future = new CompletableFuture<>(); + future.completeExceptionally(cause); + return future; + } +} diff --git a/tarantool-pooling/src/test/java/io/tarantool/pool/support/StubClient.java b/tarantool-pooling/src/test/java/io/tarantool/pool/support/StubClient.java index 6a06254c..80df51fe 100644 --- a/tarantool-pooling/src/test/java/io/tarantool/pool/support/StubClient.java +++ b/tarantool-pooling/src/test/java/io/tarantool/pool/support/StubClient.java @@ -6,6 +6,7 @@ package io.tarantool.pool.support; import java.io.IOException; +import java.net.InetSocketAddress; import java.util.Queue; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentLinkedQueue; @@ -22,6 +23,7 @@ import io.tarantool.core.protocol.IProtoRawResponse; import io.tarantool.core.protocol.IProtoRequestOpts; import io.tarantool.core.protocol.IProtoResponse; +import io.tarantool.core.protocol.requests.IProtoAuth.AuthType; import io.tarantool.core.protocol.requests.IProtoConstant; /** @@ -35,6 +37,11 @@ *

The answers are taken from the queue in the order of their scripting. When the queue is empty, * the default answer is used: a successful ping for {@link #create()}, a failed ping for {@link * #failing(Throwable)}. + * + *

The stub also scripts the steps a pool entry makes to connect the client: {@code connect}, + * {@code authorize}, {@code awaitConnectionReady} and {@code close}. Every such step succeeds + * immediately by default. The first check of a connection without a user is a ping, so it is + * scripted with the ping answers. */ public final class StubClient { @@ -42,7 +49,18 @@ public final class StubClient { private final Queue>> outcomes = new ConcurrentLinkedQueue<>(); private final AtomicInteger pingCount = new AtomicInteger(); + private final AtomicInteger connectCalls = new AtomicInteger(); + private final AtomicInteger authorizeCalls = new AtomicInteger(); + private final AtomicInteger readyCalls = new AtomicInteger(); + private final AtomicInteger closeCalls = new AtomicInteger(); private volatile Supplier> defaultOutcome; + private volatile Supplier> connectOutcome = StubClient::done; + private volatile Supplier> authorizeOutcome = + StubClient::okResponse; + private volatile Supplier> readyOutcome = StubClient::done; + private volatile Exception closeFailure; + private volatile String lastUser; + private volatile String lastPassword; private StubClient() { this.client = Mockito.mock(IProtoClient.class); @@ -50,6 +68,45 @@ private StubClient() { Mockito.when(this.client.ping(Mockito.any(IProtoRequestOpts.class))) .thenAnswer(invocation -> nextOutcome()); Mockito.when(this.client.ping()).thenAnswer(invocation -> nextOutcome()); + Mockito.when( + this.client.connect( + Mockito.any(InetSocketAddress.class), Mockito.anyLong(), Mockito.anyBoolean())) + .thenAnswer( + invocation -> { + this.connectCalls.incrementAndGet(); + return this.connectOutcome.get(); + }); + Mockito.when( + this.client.authorize(Mockito.anyString(), Mockito.any(), Mockito.any(AuthType.class))) + .thenAnswer( + invocation -> { + this.authorizeCalls.incrementAndGet(); + final Object[] args = invocation.getArguments(); + this.lastUser = (String) args[0]; + this.lastPassword = (String) args[1]; + return this.authorizeOutcome.get(); + }); + Mockito.when(this.client.awaitConnectionReady()) + .thenAnswer( + invocation -> { + this.readyCalls.incrementAndGet(); + return this.readyOutcome.get(); + }); + try { + Mockito.doAnswer( + invocation -> { + this.closeCalls.incrementAndGet(); + final Exception failure = this.closeFailure; + if (failure != null) { + throw failure; + } + return null; + }) + .when(this.client) + .close(); + } catch (Exception e) { + throw new IllegalStateException(e); + } } /** @@ -162,6 +219,151 @@ public StubClient nextPingReturnsFuture(CompletableFuture future return this; } + /** + * Makes {@code connect} fail with the given cause. + * + * @param cause the cause of the failure + * @return this stub instance + */ + public StubClient connectFails(Throwable cause) { + this.connectOutcome = () -> failed(cause); + return this; + } + + /** + * Makes {@code connect} throw synchronously, without returning a future. + * + * @param exception the exception to throw + * @return this stub instance + */ + public StubClient connectThrows(RuntimeException exception) { + this.connectOutcome = + () -> { + throw exception; + }; + return this; + } + + /** + * Makes {@code connect} return the given future: the test completes it at a chosen moment. + * + * @param future the future to return + * @return this stub instance + */ + public StubClient connectReturns(CompletableFuture future) { + this.connectOutcome = () -> future; + return this; + } + + /** + * Makes {@code connect} run the given supplier inside the call and return its future. The test + * may use it to send an event to a machine from the middle of a transition. + * + * @param answer the supplier of the future + * @return this stub instance + */ + public StubClient connectAnswers(Supplier> answer) { + this.connectOutcome = answer; + return this; + } + + /** + * Makes {@code authorize} fail with the given cause. + * + * @param cause the cause of the failure + * @return this stub instance + */ + public StubClient authorizeFails(Throwable cause) { + this.authorizeOutcome = () -> failed(cause); + return this; + } + + /** + * Makes {@code awaitConnectionReady} fail with the given cause. + * + * @param cause the cause of the failure + * @return this stub instance + */ + public StubClient readyFails(Throwable cause) { + this.readyOutcome = () -> failed(cause); + return this; + } + + /** + * Makes {@code close} throw the given exception. The call is still counted. + * + * @param exception the exception to throw + * @return this stub instance + */ + public StubClient closeThrows(Exception exception) { + this.closeFailure = exception; + return this; + } + + /** + * Returns the count of the {@code connect} calls. + * + * @return the count of the calls + */ + public int connectCalls() { + return this.connectCalls.get(); + } + + /** + * Returns the count of the {@code authorize} calls. + * + * @return the count of the calls + */ + public int authorizeCalls() { + return this.authorizeCalls.get(); + } + + /** + * Returns the count of the {@code awaitConnectionReady} calls. + * + * @return the count of the calls + */ + public int readyCalls() { + return this.readyCalls.get(); + } + + /** + * Returns the count of the {@code close} calls. + * + * @return the count of the calls + */ + public int closeCalls() { + return this.closeCalls.get(); + } + + /** + * Returns the user passed to the last {@code authorize} call. + * + * @return the user or {@code null} if there was no call + */ + public String lastUser() { + return this.lastUser; + } + + /** + * Returns the password passed to the last {@code authorize} call. + * + * @return the password or {@code null} if there was no call + */ + public String lastPassword() { + return this.lastPassword; + } + + private static CompletableFuture done() { + return CompletableFuture.completedFuture(null); + } + + private static CompletableFuture failed(Throwable cause) { + final CompletableFuture failed = new CompletableFuture<>(); + failed.completeExceptionally(cause); + return failed; + } + /** * Returns the count of the pings that have been sent to the stub. *