Skip to content
Merged
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
Expand Up @@ -24,7 +24,6 @@
import io.vertx.sqlclient.impl.command.CommandResponse;

import java.util.ArrayDeque;
import java.util.Iterator;

public class MySQLCodec extends CombinedChannelDuplexHandler<MySQLDecoder, MySQLEncoder> {

Expand All @@ -48,8 +47,16 @@ public void handlerAdded(ChannelHandlerContext ctx) throws Exception {

@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
clearInflightCommands(ClosedConnectionException.INSTANCE);
super.channelInactive(ctx);
if (failure == null) {
failure = ClosedConnectionException.INSTANCE;
}
try {
// Let the connection handle the close before the commands fail.
// A failure handler then cannot give the closed connection to a pool waiter.
super.channelInactive(ctx);
} finally {
clearInflightCommands(ClosedConnectionException.INSTANCE);
}
}

public boolean add(CommandCodec<?, ?> codec) {
Expand Down Expand Up @@ -77,26 +84,26 @@ void failAndClose(Throwable cause) {
}

private void clearInflightCommands(Throwable cause) {
for (Iterator<CommandCodec<?, ?>> it = inflight.iterator(); it.hasNext(); ) {
CommandCodec<?, ?> codec = it.next();
it.remove();
CommandCodec<?, ?> codec;
while ((codec = inflight.poll()) != null) {
fail(codec, cause);
}
}

private void fail(CommandCodec<?, ?> codec, Throwable cause) {
if (failure == null) {
failure = cause;
CommandResponse<Object> failure = CommandResponse.failure(cause);
failure.cmd = (CommandBase) codec.cmd;
chctx.fireChannelRead(failure);
}
CommandResponse<Object> response = CommandResponse.failure(cause);
response.cmd = (CommandBase) codec.cmd;
chctx.fireChannelRead(response);
}

/**
* check the pending command queue and complete handling the command directly if the command request will not receive a server response
*/
void checkFireAndForgetCommands() {
if (failure != null) {
// The pending commands fail when the channel becomes inactive
return;
}
// check if there is any completed command
CommandCodec<?, ?> commandCodec;
while ((commandCodec = inflight.peek()) != null && commandCodec.expectNoResponsePacket()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
/*
* Copyright (c) 2011-2026 Contributors to the Eclipse Foundation
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
* which is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
*/
package io.vertx.mysqlclient;

import io.vertx.core.Future;
import io.vertx.core.Promise;
import io.vertx.core.Vertx;
import io.vertx.ext.unit.Async;
import io.vertx.ext.unit.TestContext;
import io.vertx.ext.unit.junit.Timeout;
import io.vertx.ext.unit.junit.VertxUnitRunner;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.PoolOptions;
import io.vertx.sqlclient.ProxyServer;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.RowSet;
import io.vertx.sqlclient.impl.SocketConnectionBase;
import io.vertx.sqlclient.impl.SqlConnectionBase;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;

/**
* Checks that commands complete when the network connection to the server is lost.
*/
@RunWith(VertxUnitRunner.class)
public class MySQLConnectionLossTest extends MySQLTestBase {

@Rule
public Timeout timeout = Timeout.seconds(30);

private final AtomicBoolean loseNextCommand = new AtomicBoolean();
private Vertx vertx;
private MySQLConnectOptions proxyOptions;

@Before
public void setUp(TestContext ctx) {
vertx = Vertx.vertx();
ProxyServer proxy = ProxyServer.create(vertx, options.getPort(), options.getHost());
proxy.proxyHandler(conn -> {
AtomicBoolean lost = new AtomicBoolean();
conn.clientHandler(buffer -> {
if (lost.get() || loseNextCommand.compareAndSet(true, false)) {
// Drop the command and close both sockets, as a network failure does
lost.set(true);
conn.close();
} else {
conn.serverSocket().write(buffer);
}
});
conn.connect();
});
proxy.listen(8080, "localhost", ctx.asyncAssertSuccess());
proxyOptions = new MySQLConnectOptions(options)
.setHost("localhost")
.setPort(8080);
}

@After
public void tearDown(TestContext ctx) {
vertx.close().onComplete(ctx.asyncAssertSuccess());
}

@Test
public void testRollbackFromAQueryFailureHandlerCompletes(TestContext ctx) {
Async async = ctx.async();
MySQLConnection.connect(vertx, proxyOptions).onComplete(ctx.asyncAssertSuccess(conn -> {
conn.begin().onComplete(ctx.asyncAssertSuccess(tx -> {
loseNextCommand.set(true);
conn.query("SELECT 1").execute().onComplete(ctx.asyncAssertFailure(err -> {
// A transaction manager rolls back when a statement fails
tx.rollback().onComplete(ctx.asyncAssertFailure(v -> async.complete()));
}));
}));
}));
}

@Test
public void testPoolWaitersUseANewConnectionAfterTheConnectionIsLost(TestContext ctx) {
int waiters = 20;
Async async = ctx.async(waiters);
Pool pool = MySQLPool.pool(vertx, proxyOptions, new PoolOptions().setMaxSize(1));
vertx.runOnContext(v -> pool.getConnection().onComplete(ctx.asyncAssertSuccess(conn -> {
loseNextCommand.set(true);
conn.query("SELECT 1").execute().onComplete(ctx.asyncAssertFailure(err -> {
// A session returns its connection to the pool when a statement fails
conn.close();
}));
// The only pool connection is in use, so these queries wait for a connection
for (int i = 0; i < waiters; i++) {
pool.query("SELECT 1").execute().onComplete(ctx.asyncAssertSuccess(rows -> {
ctx.assertEquals(1, rows.iterator().next().getInteger(0));
async.countDown();
}));
}
})));
}

@Test
public void testPipelinedCommandsFailOnceWhenTheConnectionIsLost(TestContext ctx) {
Async async = ctx.async();
MySQLConnectOptions pipelined = new MySQLConnectOptions(proxyOptions).setPipeliningLimit(4);
MySQLConnection.connect(vertx, pipelined).onComplete(ctx.asyncAssertSuccess(conn -> {
conn.prepare("SELECT ?").onComplete(ctx.asyncAssertSuccess(statement -> {
AtomicInteger closes = new AtomicInteger();
conn.closeHandler(v -> closes.incrementAndGet());
loseNextCommand.set(true);
Future<RowSet<Row>> first = conn.query("SELECT 1").execute();
Future<RowSet<Row>> second = conn.query("SELECT 2").execute();
// The statement close expects no server response, but it waits behind the queries
Future<Void> close = statement.close();
Future<RowSet<Row>> last = conn.query("SELECT 3").execute();
Promise<RowSet<Row>> fromFailureHandler = Promise.promise();
second.onFailure(err -> conn.query("SELECT 4").execute().onComplete(fromFailureHandler));
List<Future<?>> commands = Arrays.asList(first, second, close, last, fromFailureHandler.future());
Future.join(commands).onComplete(ar -> {
for (Future<?> command : commands) {
ctx.assertTrue(command.failed());
}
ctx.assertEquals(1, closes.get());
SocketConnectionBase socket = (SocketConnectionBase) ((SqlConnectionBase<?>) conn).unwrap();
ctx.assertEquals(0, socket.inflight());
async.complete();
});
}));
}));
}
}
Loading
Loading