This is an automated email from the ASF dual-hosted git repository. rmaucher pushed a commit to branch 9.0.x in repository https://gitbox.apache.org/repos/asf/tomcat.git
commit daf109661dae17e20549f3d1c1b1169627c47f44 Author: opencode <[email protected]> AuthorDate: Mon Nov 23 15:54:37 2026 +0100 Revert "Send the JDBC 4.3 request boundary hints around a pooled borrow" This reverts commit 7c6bed669bd0844456afc40908d7f82d5012dacd. The JDBC 4.3 beginRequest()/endRequest() hints are not necessarily no-ops. A driver that implements endRequest() to restore request-local connection state may close every statement opened during the request. The statement cache deliberately parks PreparedStatements across connection returns, so such a driver closes the parked statements at endRequest() while the cache still hands them out; the next borrower then obtains a closed statement and fails on its first use, as the SQL Server driver does with "The statement is closed." Remove the request boundary hints and the tests that asserted them. --- .../apache/tomcat/jdbc/pool/ConnectionPool.java | 68 ------ .../tomcat/jdbc/pool/util/LocalStrings.properties | 2 - .../tomcat/jdbc/pool/AbortEndsTheBorrowBase.java | 61 +---- .../tomcat/jdbc/pool/RequestBoundariesBase.java | 248 --------------------- .../tomcat/jdbc/pool/SetupVsCloseRaceBase.java | 5 +- .../tomcat/jdbc/pool/TestConnectionSetup.java | 4 - 6 files changed, 5 insertions(+), 383 deletions(-) diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java index 489b9d2cb8..97346c8164 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/ConnectionPool.java @@ -19,8 +19,6 @@ package org.apache.tomcat.jdbc.pool; import java.lang.ref.WeakReference; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.security.AccessController; import java.security.PrivilegedAction; @@ -91,18 +89,6 @@ public class ConnectionPool { */ private static final long WAIT_SLICE_MILLIS = 500; - /** - * The JDBC 4.3 <code>beginRequest()</code> hint, looked up by reflection because this module compiles against Java - * 8, whose {@link java.sql.Connection} does not declare it; on a runtime that predates JDBC 4.3 the lookup yields - * null and the hint is not sent. - */ - private static final Method BEGIN_REQUEST = getRequestHintMethod("beginRequest"); - - /** - * The counterpart of {@link #BEGIN_REQUEST}, sent when the application returns the connection to the pool. - */ - private static final Method END_REQUEST = getRequestHintMethod("endRequest"); - /** * Carries the size of the pool, instead of relying on a queue implementation that usually iterates over to get an * exact count @@ -582,12 +568,6 @@ public class ConnectionPool { // exists for anyone else: no call of this borrow can precede this point, and until the next // borrow's reset clears it again, the tail refuses every other handle as an ended borrow. tail.setBorrowHandle(connection); - // The handle exists and the borrow is about to start: send the - // JDBC 4.3 hint that opens the request, so a driver that - // optimises per-request session handling knows the unit of work - // begins here. The matching endRequest() is sent at the return, - // in returnConnection(). - invokeRequestHint(BEGIN_REQUEST, con.getConnection()); } catch (Throwable x) { ExceptionUtils.handleThrowable(x); SQLException s = new SQLException(); @@ -664,47 +644,6 @@ public class ConnectionPool { } } - /** - * Looks up one of the JDBC 4.3 request boundary hint methods on {@link java.sql.Connection} by name, as they are - * absent from the Java 8 API this module compiles against. - * - * @param methodName the name of the hint method - * - * @return the method, or <code>null</code> on a runtime that predates JDBC 4.3 - */ - private static Method getRequestHintMethod(String methodName) { - try { - return Connection.class.getMethod(methodName); - } catch (NoSuchMethodException | SecurityException x) { - // Java 8 and earlier has no request boundary hints; a runtime that refuses the lookup for security - // reasons likewise has none the pool may use. - return null; - } - } - - /** - * Sends one of the JDBC 4.3 request boundary hints to a physical connection. The hint is advisory - the - * specification lets the driver treat it as a no-op - so a driver that refuses one does not fail the borrow or the - * return around it; the refusal is logged with the driver's own cause. - * - * @param hint one of the hint methods, or <code>null</code> when running where they do not exist - * @param connection the physical connection to hint - */ - private static void invokeRequestHint(Method hint, Connection connection) { - if (hint == null) { - return; - } - try { - hint.invoke(connection); - } catch (InvocationTargetException x) { - log.warn(MessageFactory.get("connectionPool.requestHintRefused", hint.getName()), - PoolUtilities.maskCredentials(x.getTargetException())); - } catch (ReflectiveOperationException | IllegalArgumentException x) { - log.warn(MessageFactory.get("connectionPool.unableToSendRequestHint", hint.getName()), - PoolUtilities.maskCredentials(x)); - } - } - /** * Creates and caches a {@link java.lang.reflect.Constructor} used to instantiate the proxy object of the requested * kind (with or without the XAConnection interface). We cache these, since the creation of a constructor is fairly @@ -2215,13 +2154,6 @@ public class ConnectionPool { } con.setStackTrace(null); con.setTimestamp(System.currentTimeMillis()); - // The application is done with the connection: - // close the JDBC 4.3 request that beginRequest() - // opened in setupConnection(). A connection - // discarded instead of going back to the pool is - // not hinted; it is about to be closed, which - // subsumes the hint. - invokeRequestHint(END_REQUEST, con.getConnection()); if (isClosed()) { // The pool closed while this return was in // flight: the checks above each read the flag diff --git a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/util/LocalStrings.properties b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/util/LocalStrings.properties index 60348d76ee..145637ad4b 100644 --- a/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/util/LocalStrings.properties +++ b/modules/jdbc-pool/src/main/java/org/apache/tomcat/jdbc/pool/util/LocalStrings.properties @@ -64,7 +64,6 @@ connectionPool.poolEmptyNoWait=[{0}] NoWait: Pool empty. Unable to fetch a conne connectionPool.poolEmptyTimeout=[{0}] Timeout: Pool empty. Unable to fetch a connection in {1} seconds, none available[size:{2}; busy:{3}; idle:{4}; lastwait:{5}]. connectionPool.poolMisconfigured=Connection pool is misconfigured, doesn''t support async retrieval. Set the ''fairQueue'' property to ''true'' connectionPool.poolWaitInterrupted=Pool wait interrupted. -connectionPool.requestHintRefused=The request boundary hint [{0}] was refused by the driver connectionPool.statementCacheBeforeQueryTimeout=The [StatementCache] interceptor is configured before [QueryTimeoutInterceptor]. A statement cache hit is answered by the cache without invoking the timeout interceptor, and a statement recycled into the cache carries no timeout, so cached statements run without a query timeout. List QueryTimeoutInterceptor before StatementCache in the jdbcInterceptors configuration. connectionPool.statementCacheBeforeStatementFinalizer=The [StatementCache] interceptor is configured before [StatementFinalizer]. The finalizer tracks the statements prepared beneath the cache and closes the still open ones when the connection is returned, while a statement parked in the cache is deliberately left open, so the cache does not park statements in this order and nothing is cached. List StatementFinalizer before StatementCache in the jdbcInterceptors configuration. connectionPool.suspectConnectionReturned=Connection({0}) that has been marked suspect was returned. The processing time is {1} ms. @@ -80,7 +79,6 @@ connectionPool.unableToInstantiateInterceptorChain=Unable to instantiate interce connectionPool.unableToParseInterceptorChain=Unable to parse the interceptor configuration. connectionPool.unableToResetInterceptor=Unable to reset interceptor [{0}]. connectionPool.unableToReturnConnection=Unable to return connection [{0}] to the pool, closing it. -connectionPool.unableToSendRequestHint=Unable to send the request boundary hint [{0}] connectionPool.unableToStartJmx=Unable to start JMX integration for connection pool. Instance[{0}] can''t be monitored. connectionPool.unableToTestIdleConnection=Unable to test idle connection [{0}], closing it. connectionPool.unableToTerminateTransaction=Unable to terminate transaction, connection will be closed. diff --git a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/AbortEndsTheBorrowBase.java b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/AbortEndsTheBorrowBase.java index 1c1d96518f..8e2c04765e 100644 --- a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/AbortEndsTheBorrowBase.java +++ b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/AbortEndsTheBorrowBase.java @@ -35,7 +35,6 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Logger; import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.Test; import org.apache.tomcat.jdbc.JdbcPoolBaseTest; @@ -668,65 +667,19 @@ abstract class AbortEndsTheBorrowBase extends JdbcPoolBaseTest { awaitSessions(0); } - @Test - void anAbortTakesTheSessionThroughTheDisconnectHookWithoutEndingTheRequest() - throws Exception { - assumeRequestHintsExist(); - SpecAbortDriver.ABORTS.set(0); - SpecAbortDriver.BEGIN_REQUESTS.set(0); - SpecAbortDriver.END_REQUESTS.set(0); - DisconnectRecordingInterceptor.DISCONNECTS.set(0); - DataSource ds = newDataSource(); - ds.setDriverClassName(SpecAbortDriver.class.getName()); - ds.getPoolProperties().setInitialSize(0); - ds.getPoolProperties().setJdbcInterceptors( - DisconnectRecordingInterceptor.class.getName()); - ds.createPool(); - - Connection pooled = ds.getConnection(); - Assertions.assertEquals(1, SpecAbortDriver.BEGIN_REQUESTS.get(), - "precondition: the borrow opened its request at the driver"); - Assertions.assertEquals(0, SpecAbortDriver.END_REQUESTS.get()); - - pooled.abort(DIRECT_EXECUTOR); - - Assertions.assertEquals(0, SpecAbortDriver.END_REQUESTS.get(), - "a session taken out of service is not hinted - its close " - + "subsumes the hint, as on every other discard path"); - Assertions.assertEquals(1, DisconnectRecordingInterceptor.DISCONNECTS.get(), - "the interceptors must be told the session is gone, once, " - + "the same disconnect the release path runs"); - } - - /* The hints do not exist before Java 9; same lookup the pool performs. */ - private static void assumeRequestHintsExist() { - boolean exists; - try { - Connection.class.getMethod("beginRequest"); - exists = true; - } catch (NoSuchMethodException e) { - exists = false; - } - Assumptions.assumeTrue(exists, - "java.sql.Connection has no request boundary hints before Java 9"); - } - /* * A driver whose sessions honor java.sql.Connection.abort the way the * specification describes it, unlike H2's - H2's abort neither closes * the session nor rejects a null executor (both measured against * 2.2.220). These sessions count every abort that reaches the driver, * no-op when already closed, throw the prescribed SQLException for a - * null executor, and otherwise close the physical session. They also - * count the JDBC 4.3 request boundary hints, so a test can see that the - * abort path sends no endRequest. Configured through driverClassName, so - * it must stay a public static class with a no-arg constructor. + * null executor, and otherwise close the physical session. Configured + * through driverClassName, so it must stay a public static class with a + * no-arg constructor. */ public static class SpecAbortDriver implements Driver { static final AtomicInteger ABORTS = new AtomicInteger(); - static final AtomicInteger BEGIN_REQUESTS = new AtomicInteger(); - static final AtomicInteger END_REQUESTS = new AtomicInteger(); private final Driver delegate = new org.h2.Driver(); @@ -756,14 +709,6 @@ abstract class AbortEndsTheBorrowBase extends JdbcPoolBaseTest { real.close(); // marks closed, closes the session return null; } - case "beginRequest": { - BEGIN_REQUESTS.incrementAndGet(); - break; - } - case "endRequest": { - END_REQUESTS.incrementAndGet(); - break; - } default: { break; } diff --git a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/RequestBoundariesBase.java b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/RequestBoundariesBase.java deleted file mode 100644 index a2b1982487..0000000000 --- a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/RequestBoundariesBase.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.tomcat.jdbc.pool; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.lang.reflect.Proxy; -import java.sql.Connection; -import java.sql.Driver; -import java.sql.DriverPropertyInfo; -import java.sql.SQLException; -import java.sql.SQLFeatureNotSupportedException; -import java.util.Properties; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.logging.Logger; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Assumptions; -import org.junit.jupiter.api.Test; - -import org.apache.tomcat.jdbc.JdbcPoolBaseTest; - -/** - * The JDBC 4.3 request boundary hints: the pool is expected to call - * {@code Connection.beginRequest()} on the physical connection as it hands - * that connection to the application and {@code Connection.endRequest()} - * as the application returns it, so a driver that optimises session - * handling around a unit of work can do so. A hint is advisory, so a - * driver that refuses one must not fail the borrow or the return around - * it, and the pool still has to hand out a working, reusable connection. - * - * <p>Scenario harvested from the contribution of pull request 677, which - * counted the hints on a stub driver; here the counting proxy sits on the - * H2 connection itself, so the assertions also prove the hints travelled - * on the physical session and bracketed each borrow.</p> - */ -abstract class RequestBoundariesBase extends JdbcPoolBaseTest { - - private static final AtomicInteger BEGIN_REQUEST_COUNT = new AtomicInteger(); - private static final AtomicInteger END_REQUEST_COUNT = new AtomicInteger(); - - /* - * Same lookup the pool itself performs: on a Java 8 runtime the hints - * do not exist, the pool sends none, and there is nothing for this - * class to observe. - */ - private static void assumeRequestHintsExist() { - boolean exists; - try { - Connection.class.getMethod("beginRequest"); - exists = true; - } catch (NoSuchMethodException e) { - exists = false; - } - Assumptions.assumeTrue(exists, - "java.sql.Connection has no request boundary hints before Java 9"); - } - - /* - * The hints must be counted where the pool sends them: at the physical - * connection. A driver configured by class name wraps whatever the H2 - * driver returns in a proxy that counts the two hint methods before - * delegating them to H2, and the pool is configured to use that driver - * against the real database. - */ - private DataSource hintCountingDataSource(Class<? extends Driver> driverClass) - throws SQLException { - BEGIN_REQUEST_COUNT.set(0); - END_REQUEST_COUNT.set(0); - DataSource ds = newDataSource(); - ds.setDriverClassName(driverClass.getName()); - // start empty: no physical connection, so no pool-start traffic to - // discount from the counts asserted below - ds.getPoolProperties().setInitialSize(0); - ds.createPool(); - return ds; - } - - @Test - void hintsBracketEachBorrowOfTheSameSession() throws Exception { - assumeRequestHintsExist(); - DataSource ds = hintCountingDataSource(HintCountingDriver.class); - - Assertions.assertEquals(0, BEGIN_REQUEST_COUNT.get(), "no borrow yet"); - Assertions.assertEquals(0, END_REQUEST_COUNT.get(), "no borrow yet"); - - Connection first = ds.getConnection(); - Assertions.assertEquals(1, BEGIN_REQUEST_COUNT.get(), - "beginRequest() must reach the driver as the connection is handed out"); - Assertions.assertEquals(0, END_REQUEST_COUNT.get(), - "endRequest() belongs to the return, not the borrow"); - - first.close(); - Assertions.assertEquals(1, END_REQUEST_COUNT.get(), - "endRequest() must reach the driver as the connection is returned"); - - // a second borrow on the same physical session hints again - the - // hints bracket every unit of work, not just the first one - Connection second = ds.getConnection(); - Assertions.assertEquals(2, BEGIN_REQUEST_COUNT.get()); - Assertions.assertEquals(1, END_REQUEST_COUNT.get()); - second.close(); - Assertions.assertEquals(2, END_REQUEST_COUNT.get()); - - Assertions.assertEquals(1, poolSessions(), - "both borrows ran on the same physical session"); - } - - @Test - void aDriverThatRefusesTheHintsNeitherFailsTheBorrowNorTheReturn() throws Exception { - assumeRequestHintsExist(); - DataSource ds = hintCountingDataSource(FailingHintDriver.class); - - try (Connection con = ds.getConnection()) { - Assertions.assertEquals(1, BEGIN_REQUEST_COUNT.get(), - "the refused hint must still have been attempted"); - // the connection itself is unaffected by the refusal - con.createStatement().close(); - } - Assertions.assertEquals(1, END_REQUEST_COUNT.get(), - "the refused hint must not strand the return of the connection"); - - // the connection stayed poolable across the refused hints - try (@SuppressWarnings("unused") Connection con = ds.getConnection()) { - Assertions.assertEquals(2, BEGIN_REQUEST_COUNT.get()); - } - Assertions.assertEquals(1, poolSessions(), - "the refused hints must not have cost the pool its session"); - } - - /** - * Driver that counts the request boundary hints reaching the physical - * connection it returns. Configured through {@code driverClassName}, - * so it must stay a public static class with a no-arg constructor. - */ - public static class HintCountingDriver implements Driver { - - private final Driver delegate = new org.h2.Driver(); - - @Override - public Connection connect(String url, Properties info) throws SQLException { - Connection connection = delegate.connect(url, info); - if (connection == null) { - return null; - } - return (Connection) Proxy.newProxyInstance( - HintCountingDriver.class.getClassLoader(), - new Class<?>[] { Connection.class }, - hintCounter(connection, refuseHints())); - } - - /* - * Overridden by the subclass below; a driver instantiated by class - * name can only be told apart by its own behaviour. - */ - protected boolean refuseHints() { - return false; - } - - @Override - public boolean acceptsURL(String url) throws SQLException { - return delegate.acceptsURL(url); - } - - @Override - public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException { - return delegate.getPropertyInfo(url, info); - } - - @Override - public int getMajorVersion() { - return delegate.getMajorVersion(); - } - - @Override - public int getMinorVersion() { - return delegate.getMinorVersion(); - } - - @Override - public boolean jdbcCompliant() { - return delegate.jdbcCompliant(); - } - - @Override - public Logger getParentLogger() throws SQLFeatureNotSupportedException { - return delegate.getParentLogger(); - } - } - - /** - * Driver that additionally refuses both hints, to pin that the pool - * treats a refused hint as the advisory failure it is. - */ - public static class FailingHintDriver extends HintCountingDriver { - @Override - protected boolean refuseHints() { - return true; - } - } - - /* - * Counts the two hint methods by name and delegates everything, the - * hints included, to the H2 connection; by name, because this suite - * still compiles against Java 8. The refusing configuration makes the - * two hints throw instead of delegating, like a driver that declines - * to take them. - */ - private static InvocationHandler hintCounter(Connection vendor, boolean refuseHints) { - return new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - String name = method.getName(); - if ("beginRequest".equals(name)) { - BEGIN_REQUEST_COUNT.incrementAndGet(); - if (refuseHints) { - throw new SQLException("beginRequest() refused by the test driver"); - } - } else if ("endRequest".equals(name)) { - END_REQUEST_COUNT.incrementAndGet(); - if (refuseHints) { - throw new SQLException("endRequest() refused by the test driver"); - } - } - try { - return method.invoke(vendor, args); - } catch (InvocationTargetException x) { - throw x.getCause(); - } - } - }; - } -} diff --git a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/SetupVsCloseRaceBase.java b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/SetupVsCloseRaceBase.java index a6e6900e9c..7dd2f6fdd8 100644 --- a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/SetupVsCloseRaceBase.java +++ b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/SetupVsCloseRaceBase.java @@ -35,9 +35,8 @@ import org.apache.tomcat.jdbc.JdbcPoolBaseTest; /** * A close can set the pooled connection's released flag and begin the physical close while a borrow is still in * {@link ConnectionPool#setupConnection(PooledConnection)}. The setup used to finish building a handle from that - * released connection, and the only thing that failed such a borrow on a current JDK was the JDBC 4.3 beginRequest hint - * receiving the nulled physical connection by accident; where that hint is absent or the physical close has not nulled - * the field yet, the caller received an inert handle instead of an {@link SQLException}. + * released connection and hand the caller an inert handle instead of an {@link SQLException}; it must now fail the + * borrow whenever the connection it is setting up has been released. */ abstract class SetupVsCloseRaceBase extends JdbcPoolBaseTest { diff --git a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestConnectionSetup.java b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestConnectionSetup.java index cedb8c08a6..64bca4fc82 100644 --- a/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestConnectionSetup.java +++ b/modules/jdbc-pool/src/test/java/org/apache/tomcat/jdbc/pool/TestConnectionSetup.java @@ -38,10 +38,6 @@ class TestConnectionSetup { class InitSqlCommittedAtInitialization extends InitSqlCommittedAtInitializationBase { } - @Nested - class RequestBoundaries extends RequestBoundariesBase { - } - @Nested class LiveDriverChange extends LiveDriverChangeBase { } --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
