Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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) {}
}
Original file line number Diff line number Diff line change
@@ -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.
*
* <p>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.
*
* <p>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);
}
}
Original file line number Diff line number Diff line change
@@ -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));
}
}
Original file line number Diff line number Diff line change
@@ -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);
}
Loading
Loading