diff --git a/vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/MySQLCodec.java b/vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/MySQLCodec.java index 0e6f057325..655283de1d 100644 --- a/vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/MySQLCodec.java +++ b/vertx-mysql-client/src/main/java/io/vertx/mysqlclient/impl/codec/MySQLCodec.java @@ -24,7 +24,6 @@ import io.vertx.sqlclient.impl.command.CommandResponse; import java.util.ArrayDeque; -import java.util.Iterator; public class MySQLCodec extends CombinedChannelDuplexHandler { @@ -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) { @@ -77,26 +84,26 @@ void failAndClose(Throwable cause) { } private void clearInflightCommands(Throwable cause) { - for (Iterator> 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 failure = CommandResponse.failure(cause); - failure.cmd = (CommandBase) codec.cmd; - chctx.fireChannelRead(failure); - } + CommandResponse 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()) { diff --git a/vertx-mysql-client/src/test/java/io/vertx/mysqlclient/MySQLConnectionLossTest.java b/vertx-mysql-client/src/test/java/io/vertx/mysqlclient/MySQLConnectionLossTest.java new file mode 100644 index 0000000000..134ff6677b --- /dev/null +++ b/vertx-mysql-client/src/test/java/io/vertx/mysqlclient/MySQLConnectionLossTest.java @@ -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> first = conn.query("SELECT 1").execute(); + Future> second = conn.query("SELECT 2").execute(); + // The statement close expects no server response, but it waits behind the queries + Future close = statement.close(); + Future> last = conn.query("SELECT 3").execute(); + Promise> fromFailureHandler = Promise.promise(); + second.onFailure(err -> conn.query("SELECT 4").execute().onComplete(fromFailureHandler)); + List> 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(); + }); + })); + })); + } +} diff --git a/vertx-mysql-client/src/test/java/io/vertx/mysqlclient/impl/codec/MySQLCodecTest.java b/vertx-mysql-client/src/test/java/io/vertx/mysqlclient/impl/codec/MySQLCodecTest.java new file mode 100644 index 0000000000..7666d506dd --- /dev/null +++ b/vertx-mysql-client/src/test/java/io/vertx/mysqlclient/impl/codec/MySQLCodecTest.java @@ -0,0 +1,221 @@ +/* + * 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.impl.codec; + +import io.netty.buffer.ByteBuf; +import io.netty.buffer.Unpooled; +import io.netty.channel.ChannelHandlerContext; +import io.netty.channel.ChannelInboundHandlerAdapter; +import io.netty.channel.embedded.EmbeddedChannel; +import io.vertx.mysqlclient.MySQLConnectOptions; +import io.vertx.mysqlclient.impl.MySQLParamDesc; +import io.vertx.mysqlclient.impl.protocol.ColumnDefinition; +import io.vertx.sqlclient.ClosedConnectionException; +import io.vertx.sqlclient.impl.QueryResultHandler; +import io.vertx.sqlclient.impl.command.CloseStatementCommand; +import io.vertx.sqlclient.impl.command.CommandBase; +import io.vertx.sqlclient.impl.command.CommandResponse; +import io.vertx.sqlclient.impl.command.QueryCommandBase; +import io.vertx.sqlclient.impl.command.SimpleQueryCommand; +import org.junit.After; +import org.junit.Test; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertSame; +import static org.junit.Assert.assertTrue; + +/** + * Checks that every command written to the codec receives exactly one response when the connection fails. + */ +public class MySQLCodecTest { + + private final List> responses = new ArrayList<>(); + private final List events = new ArrayList<>(); + private final List exceptions = new ArrayList<>(); + private CommandBase failingCommand; + private CommandBase commandWrittenOnFailure; + private EmbeddedChannel channel; + + @After + public void tearDown() { + if (channel != null) { + channel.finishAndReleaseAll(); + } + } + + @Test + public void testEveryInflightCommandFailsWhenTheConnectionCloses() { + SimpleQueryCommand first = query("SELECT 1"); + SimpleQueryCommand second = query("SELECT 2"); + connect(MySQLConnectOptions.DEFAULT_MAX_ALLOWED_PACKET); + + channel.writeOutbound(first, second); + assertTrue(responses.isEmpty()); + channel.close(); + + assertResponses(first, second); + assertFailures(ClosedConnectionException.INSTANCE); + } + + @Test + public void testCommandWrittenByAFailureHandlerFails() { + SimpleQueryCommand query = query("SELECT 1"); + SimpleQueryCommand rollback = query("ROLLBACK"); + connect(MySQLConnectOptions.DEFAULT_MAX_ALLOWED_PACKET); + // For example, a transaction rolls back when one of its queries fails + writeOnFailure(query, rollback); + + channel.writeOutbound(query); + channel.close(); + + assertResponses(query, rollback); + assertFailures(ClosedConnectionException.INSTANCE); + } + + @Test + public void testConnectionHandlesTheCloseBeforeInflightCommandsFail() { + connect(MySQLConnectOptions.DEFAULT_MAX_ALLOWED_PACKET); + + channel.writeOutbound(query("SELECT 1")); + channel.close(); + + // Otherwise a failure handler can return the closed connection to a pool waiter + assertEquals(Arrays.asList("inactive", "response"), events); + } + + @Test + public void testCommandWrittenByAFailureHandlerDoesNotCompleteAStatementClose() { + SimpleQueryCommand first = query("SELECT 1"); + CloseStatementCommand close = closeStatement(); + SimpleQueryCommand last = query("SELECT 2"); + SimpleQueryCommand rollback = query("ROLLBACK"); + connect(MySQLConnectOptions.DEFAULT_MAX_ALLOWED_PACKET); + writeOnFailure(first, rollback); + + // The statement close expects no server response, but it waits behind the first query + channel.writeOutbound(first, close, last); + channel.close(); + + assertResponses(first, rollback, close, last); + assertFailures(ClosedConnectionException.INSTANCE); + assertTrue("Unexpected exceptions: " + exceptions, exceptions.isEmpty()); + } + + @Test + public void testOversizedMessageFailsEveryCommand() { + int maxAllowedPacket = 64; + SimpleQueryCommand first = query("SELECT 1"); + CloseStatementCommand close = closeStatement(); + SimpleQueryCommand last = query("SELECT 2"); + SimpleQueryCommand rollback = query("ROLLBACK"); + connect(maxAllowedPacket); + writeOnFailure(first, rollback); + channel.writeOutbound(first, close, last); + + // The second packet of the response makes the reassembled message exceed the limit + channel.writeInbound(packet(0xFFFFFF, 0, maxAllowedPacket), packet(0xFFFFFF, 1, maxAllowedPacket)); + channel.runPendingTasks(); + + assertResponses(first, rollback, close, last); + Throwable oversized = responses.get(0).toAsyncResult().cause(); + assertTrue(String.valueOf(oversized), oversized.getMessage().contains("exceeds limit")); + assertSame(oversized, responses.get(1).toAsyncResult().cause()); + assertSame(ClosedConnectionException.INSTANCE, responses.get(2).toAsyncResult().cause()); + assertSame(ClosedConnectionException.INSTANCE, responses.get(3).toAsyncResult().cause()); + } + + private void connect(int maxAllowedPacket) { + channel = new EmbeddedChannel(new TestCodec(maxAllowedPacket), new ConnectionHandler()); + } + + private void writeOnFailure(CommandBase failing, CommandBase written) { + failingCommand = failing; + commandWrittenOnFailure = written; + } + + private void assertResponses(CommandBase... expected) { + List actual = new ArrayList<>(); + for (CommandResponse response : responses) { + actual.add(describe(response.cmd)); + } + List commands = new ArrayList<>(); + for (CommandBase command : expected) { + commands.add(describe(command)); + } + assertEquals(commands, actual); + } + + private static String describe(CommandBase command) { + return command instanceof SimpleQueryCommand ? ((SimpleQueryCommand) command).sql() : command.getClass().getSimpleName(); + } + + private void assertFailures(Throwable cause) { + for (CommandResponse response : responses) { + assertTrue(describe(response.cmd) + " did not fail", response.toAsyncResult().failed()); + assertSame(cause, response.toAsyncResult().cause()); + } + } + + private static SimpleQueryCommand query(String sql) { + return new SimpleQueryCommand<>(sql, false, false, QueryCommandBase.NULL_COLLECTOR, QueryResultHandler.NOOP_HANDLER); + } + + private static CloseStatementCommand closeStatement() { + return new CloseStatementCommand(new MySQLPreparedStatement("SELECT ?", 1, new MySQLParamDesc(new ColumnDefinition[0]), false)); + } + + private static ByteBuf packet(int payloadLength, int sequenceId, int bodyLength) { + return Unpooled.buffer() + .writeMediumLE(payloadLength) + .writeByte(sequenceId) + .writeZero(bodyLength); + } + + /** + * Sets the character set that the handshake normally sets. + */ + private static class TestCodec extends MySQLCodec { + TestCodec(int maxAllowedPacket) { + super(null, maxAllowedPacket); + outboundHandler().encodingCharset = StandardCharsets.UTF_8; + } + } + + /** + * Records what reaches the connection handler that follows the codec in the pipeline. + */ + private class ConnectionHandler extends ChannelInboundHandlerAdapter { + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) { + CommandResponse response = (CommandResponse) msg; + events.add("response"); + responses.add(response); + if (response.cmd == failingCommand) { + ctx.write(commandWrittenOnFailure); + } + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) { + events.add("inactive"); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { + exceptions.add(cause); + } + } +}