From 34fc31e31b940523dc1e2a5c7f5a2684e942b874 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9lder=20Greg=C3=B3rio?= Date: Mon, 30 Nov 2026 16:32:08 +0000 Subject: [PATCH] [JDBC] Only close the server session when one may exist Connection#close sent CloseSession on every connection and kept a list of status codes to ignore when no catalog was set. Flight SQL leaves the session mechanism to the server, so the driver now sends CloseSession only when it has seen a sign of a session: - the connection set session options, at connect time or later through Connection#setCatalog, or - the server sent a cookie, which is how sessions are typically kept. Connections to servers without sessions no longer make an extra call on close. CloseSession is now best effort, as in the ADBC Flight SQL driver. A failure is logged (at warn when the connection set session options) and does not fail close, since the channel is closed either way and an unclosed session expires on the server. This replaces the list of "no session" status codes. Previously the catalog check only looked at the catalog connection property, so a catalog set with Connection#setCatalog after connecting was treated as if there were no session. Co-Authored-By: Claude Opus 5.5 --- .../client/ArrowFlightSqlClientHandler.java | 54 +++--- .../jdbc/client/ServerSessionTracker.java | 67 +++++++ .../arrow/driver/jdbc/ConnectionTest.java | 29 ++- .../ArrowFlightSqlClientHandlerTest.java | 165 ++++++++++-------- 4 files changed, 226 insertions(+), 89 deletions(-) create mode 100644 flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ServerSessionTracker.java diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java index bd81ee0626..471e1d5459 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandler.java @@ -28,7 +28,6 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; -import java.util.EnumSet; import java.util.HashSet; import java.util.List; import java.util.Locale; @@ -88,15 +87,6 @@ public final class ArrowFlightSqlClientHandler implements AutoCloseable { @VisibleForTesting static final CallOption CLOSE_SESSION_TIMEOUT = CallOptions.timeout(5, TimeUnit.SECONDS); - // No session to close: CloseSession is unsupported or unknown, none was created, or the - // client is not (or no longer) authenticated. - private static final Set NO_SESSION_STATUS_CODES = - EnumSet.of( - FlightStatusCode.UNIMPLEMENTED, - FlightStatusCode.INVALID_ARGUMENT, - FlightStatusCode.NOT_FOUND, - FlightStatusCode.UNAUTHENTICATED); - private final String cacheKey; private final FlightSqlClient sqlClient; private final Set options = new HashSet<>(); @@ -104,6 +94,7 @@ public final class ArrowFlightSqlClientHandler implements AutoCloseable { private final boolean followEndpointLocations; private final Optional catalog; private final @Nullable FlightClientCache flightClientCache; + private final ServerSessionTracker sessionTracker; ArrowFlightSqlClientHandler( final String cacheKey, @@ -111,7 +102,8 @@ public final class ArrowFlightSqlClientHandler implements AutoCloseable { final Builder builder, final Collection credentialOptions, final Optional catalog, - final @Nullable FlightClientCache flightClientCache) { + final @Nullable FlightClientCache flightClientCache, + final ServerSessionTracker sessionTracker) { this.options.addAll(builder.options); this.options.addAll(credentialOptions); this.cacheKey = Preconditions.checkNotNull(cacheKey); @@ -120,6 +112,7 @@ public final class ArrowFlightSqlClientHandler implements AutoCloseable { this.followEndpointLocations = builder.followEndpointLocations; this.catalog = catalog; this.flightClientCache = flightClientCache; + this.sessionTracker = Preconditions.checkNotNull(sessionTracker); } /** @@ -136,10 +129,17 @@ static ArrowFlightSqlClientHandler createNewHandler( final Builder builder, final Collection options, final Optional catalog, - final @Nullable FlightClientCache flightClientCache) { + final @Nullable FlightClientCache flightClientCache, + final ServerSessionTracker sessionTracker) { final ArrowFlightSqlClientHandler handler = new ArrowFlightSqlClientHandler( - cacheKey, new FlightSqlClient(client), builder, options, catalog, flightClientCache); + cacheKey, + new FlightSqlClient(client), + builder, + options, + catalog, + flightClientCache, + sessionTracker); handler.setSetCatalogInSessionIfPresent(); return handler; } @@ -350,8 +350,13 @@ public void close() throws SQLException { } } - private void closeSession() throws SQLException { - if (!builder.ownsSession) { + /** + * Closes the server session, if the server may hold one. This is best effort: a server that does + * not support sessions may reject the call, and a session that is not closed expires on the + * server, so a failure is logged and does not fail {@link #close()}. + */ + private void closeSession() { + if (!builder.ownsSession || !sessionTracker.mayHaveSession()) { return; } final CallOption[] baseOptions = getOptions(); @@ -360,11 +365,10 @@ private void closeSession() throws SQLException { try { sqlClient.closeSession(new CloseSessionRequest(), closeSessionOptions); } catch (FlightRuntimeException fre) { - if (catalog.isEmpty() && NO_SESSION_STATUS_CODES.contains(fre.status().code())) { - logSuppressedCloseException(fre, "closing Flight SQL session"); + if (sessionTracker.isSessionOptionsSet() && !isBenignCloseException(fre)) { + LOGGER.warn("Failed to close Flight SQL session", fre); } else { - handleBenignCloseException( - fre, "Failed to close Flight SQL session.", "closing Flight SQL session"); + logSuppressedCloseException(fre, "closing Flight SQL session"); } } } @@ -510,6 +514,8 @@ public void setCatalog(final String catalog) throws SQLException { ImmutableMap.of(CATALOG, SessionOptionValueFactory.makeSessionOptionValue(catalog))); try { final SetSessionOptionsResult result = sqlClient.setSessionOptions(request, getOptions()); + // Even when it rejects an option, the server may have started a session for the request. + sessionTracker.onSessionOptionsSet(); if (result.hasErrors()) { final Map errors = result.getErrors(); for (final Map.Entry error : errors.entrySet()) { @@ -1272,6 +1278,8 @@ public ArrowFlightSqlClientHandler build() throws SQLException { } buildTimeMiddlewareFactories.add(new ClientCookieMiddleware.Factory()); + final ServerSessionTracker sessionTracker = new ServerSessionTracker(); + buildTimeMiddlewareFactories.add(sessionTracker); buildTimeMiddlewareFactories.forEach(clientBuilder::intercept); if (useEncryption) { clientBuilder.useTls(); @@ -1349,7 +1357,13 @@ public ArrowFlightSqlClientHandler build() throws SQLException { options.toArray(new CallOption[0]))); } return ArrowFlightSqlClientHandler.createNewHandler( - getCacheKey(), client, this, credentialOptions, catalog, flightClientCache); + getCacheKey(), + client, + this, + credentialOptions, + catalog, + flightClientCache, + sessionTracker); } catch (final IllegalArgumentException | GeneralSecurityException diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ServerSessionTracker.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ServerSessionTracker.java new file mode 100644 index 0000000000..aeff373c3e --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/client/ServerSessionTracker.java @@ -0,0 +1,67 @@ +/* + * 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.arrow.driver.jdbc.client; + +import java.util.concurrent.atomic.AtomicBoolean; +import org.apache.arrow.flight.CallHeaders; +import org.apache.arrow.flight.CallInfo; +import org.apache.arrow.flight.CallStatus; +import org.apache.arrow.flight.FlightClientMiddleware; + +/** + * Records whether the server may hold a session for a connection, so that closing the connection + * only sends CloseSession when there can be a session to close. + * + *

Flight SQL leaves the session mechanism to the server, typically a cookie. A session can exist + * once the client has set session options, or once the server has sent a cookie. + */ +final class ServerSessionTracker implements FlightClientMiddleware.Factory { + private static final String SET_COOKIE_HEADER = "Set-Cookie"; + + private final AtomicBoolean sessionOptionsSet = new AtomicBoolean(); + private final AtomicBoolean cookieReceived = new AtomicBoolean(); + + void onSessionOptionsSet() { + sessionOptionsSet.set(true); + } + + boolean isSessionOptionsSet() { + return sessionOptionsSet.get(); + } + + boolean mayHaveSession() { + return sessionOptionsSet.get() || cookieReceived.get(); + } + + @Override + public FlightClientMiddleware onCallStarted(final CallInfo info) { + return new FlightClientMiddleware() { + @Override + public void onBeforeSendingHeaders(final CallHeaders outgoingHeaders) {} + + @Override + public void onHeadersReceived(final CallHeaders incomingHeaders) { + if (incomingHeaders.containsKey(SET_COOKIE_HEADER)) { + cookieReceived.set(true); + } + } + + @Override + public void onCallCompleted(final CallStatus status) {} + }; + } +} diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTest.java index eda38d85ef..6e6742b1cd 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ConnectionTest.java @@ -49,6 +49,8 @@ import org.apache.arrow.driver.jdbc.utils.MockFlightSqlProducer; import org.apache.arrow.flight.FlightMethod; import org.apache.arrow.flight.FlightProducer.ServerStreamListener; +import org.apache.arrow.flight.FlightServer; +import org.apache.arrow.flight.Location; import org.apache.arrow.flight.NoOpSessionOptionValueVisitor; import org.apache.arrow.flight.SessionOptionValue; import org.apache.arrow.flight.sql.FlightSqlProducer.Schemas; @@ -650,8 +652,9 @@ public void testJdbcDriverVersionIntegration() throws Exception { } } + /** The test server sends a cookie, so the driver closes the session it may hold. */ @Test - public void testCloseWithoutCatalogClosesSession() throws Exception { + public void testCloseWithSessionCookieClosesSession() throws Exception { final Properties properties = new Properties(); properties.put(ArrowFlightConnectionProperty.USER.camelName(), userTest); properties.put(ArrowFlightConnectionProperty.PASSWORD.camelName(), passTest); @@ -671,6 +674,30 @@ public void testCloseWithoutCatalogClosesSession() throws Exception { assertEquals(closeSessionCountBefore + 1, PRODUCER.getCloseSessionCount()); } + @Test + public void testCloseOnlyClosesSessionAfterSessionOptionsAreSet() throws Exception { + final MockFlightSqlProducer producer = new MockFlightSqlProducer(); + // Without the test extension's middleware, the server sends no cookie. + try (BufferAllocator allocator = new RootAllocator(Long.MAX_VALUE); + FlightServer server = + FlightServer.builder(allocator, Location.forGrpcInsecure("localhost", 0), producer) + .build() + .start()) { + final String url = + format("jdbc:arrow-flight-sql://localhost:%d/?useEncryption=false", server.getPort()); + + try (Connection connection = DriverManager.getConnection(url)) { + connection.getMetaData(); + } + assertEquals(0, producer.getCloseSessionCount()); + + try (Connection connection = DriverManager.getConnection(url)) { + connection.setCatalog("new_catalog"); + } + assertEquals(1, producer.getCloseSessionCount()); + } + } + @Test public void testSetCatalogShouldUpdateSessionOptions() throws Exception { final Properties properties = new Properties(); diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java index 0e991253e5..2fc0f9b87d 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/client/ArrowFlightSqlClientHandlerTest.java @@ -35,19 +35,24 @@ import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Optional; +import org.apache.arrow.flight.CallHeaders; +import org.apache.arrow.flight.CallInfo; import org.apache.arrow.flight.CallOption; import org.apache.arrow.flight.CallStatus; import org.apache.arrow.flight.CloseSessionRequest; +import org.apache.arrow.flight.FlightCallHeaders; import org.apache.arrow.flight.FlightDescriptor; import org.apache.arrow.flight.FlightEndpoint; import org.apache.arrow.flight.FlightInfo; +import org.apache.arrow.flight.FlightMethod; import org.apache.arrow.flight.FlightStatusCode; import org.apache.arrow.flight.FlightStream; import org.apache.arrow.flight.Location; +import org.apache.arrow.flight.SetSessionOptionsRequest; +import org.apache.arrow.flight.SetSessionOptionsResult; import org.apache.arrow.flight.Ticket; import org.apache.arrow.flight.sql.FlightSqlClient; import org.apache.arrow.memory.BufferAllocator; @@ -56,6 +61,7 @@ import org.apache.arrow.vector.types.pojo.Schema; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.junit.jupiter.params.provider.MethodSource; import org.junit.jupiter.params.provider.ValueSource; @@ -278,8 +284,21 @@ private static ArrowFlightSqlClientHandler encryptedHandler( private static ArrowFlightSqlClientHandler handler( final FlightSqlClient sqlClient, final ArrowFlightSqlClientHandler.Builder builder) { + return handler(sqlClient, builder, new ServerSessionTracker()); + } + + private static ArrowFlightSqlClientHandler handler( + final FlightSqlClient sqlClient, + final ArrowFlightSqlClientHandler.Builder builder, + final ServerSessionTracker sessionTracker) { return new ArrowFlightSqlClientHandler( - "cacheKey", sqlClient, builder, new ArrayList<>(), Optional.empty(), null); + "cacheKey", sqlClient, builder, new ArrayList<>(), Optional.empty(), null, sessionTracker); + } + + private static ServerSessionTracker trackerWithSessionOptions() { + final ServerSessionTracker sessionTracker = new ServerSessionTracker(); + sessionTracker.onSessionOptionsSet(); + return sessionTracker; } private static FlightInfo flightInfoWithLocations(final Location... locations) { @@ -293,27 +312,12 @@ private static FlightInfo flightInfoWithLocations(final Location... locations) { @ParameterizedTest @MethodSource - public void testCloseHandlesFlightRuntimeException( - boolean throwFromCloseSession, CallStatus callStatus, boolean shouldSuppress) + public void testCloseHandlesFlightRuntimeException(CallStatus callStatus, boolean shouldSuppress) throws Exception { FlightSqlClient sqlClient = mock(FlightSqlClient.class); - String cacheKey = "cacheKey"; - Optional catalog = - throwFromCloseSession ? Optional.of("test_catalog") : Optional.empty(); - final Collection credentialOptions = new ArrayList<>(); - ArrowFlightSqlClientHandler.Builder builder = new ArrowFlightSqlClientHandler.Builder(); - - if (throwFromCloseSession) { - doThrow(callStatus.toRuntimeException()) - .when(sqlClient) - .closeSession(any(CloseSessionRequest.class), any(CallOption[].class)); - } else { - doThrow(callStatus.toRuntimeException()).when(sqlClient).close(); - } - + doThrow(callStatus.toRuntimeException()).when(sqlClient).close(); ArrowFlightSqlClientHandler sqlClientHandler = - new ArrowFlightSqlClientHandler( - cacheKey, sqlClient, builder, credentialOptions, catalog, null); + handler(sqlClient, new ArrowFlightSqlClientHandler.Builder(), trackerWithSessionOptions()); if (shouldSuppress) { assertDoesNotThrow(sqlClientHandler::close); @@ -323,77 +327,102 @@ public void testCloseHandlesFlightRuntimeException( verify(sqlClient).close(); } + private static Object[] testCloseHandlesFlightRuntimeException() { + return new Object[] { + new Object[] { + new CallStatus(FlightStatusCode.INTERNAL, null, "Connection closed after GOAWAY", null), + true + }, + new Object[] { + new CallStatus(FlightStatusCode.INTERNAL, null, "Not a benign internal error", null), false + }, + new Object[] {new CallStatus(FlightStatusCode.UNAVAILABLE, null, null, null), true}, + new Object[] {new CallStatus(FlightStatusCode.UNKNOWN, null, null, null), false}, + }; + } + @ParameterizedTest - @MethodSource - public void testCloseSessionWithoutCatalog(FlightStatusCode code, boolean shouldSuppress) - throws Exception { + @EnumSource( + value = FlightStatusCode.class, + names = {"OK"}, + mode = EnumSource.Mode.EXCLUDE) + public void testCloseSessionFailureDoesNotFailClose(FlightStatusCode code) throws Exception { FlightSqlClient sqlClient = mock(FlightSqlClient.class); doThrow(new CallStatus(code, null, null, null).toRuntimeException()) .when(sqlClient) .closeSession(any(CloseSessionRequest.class), any(CallOption[].class)); ArrowFlightSqlClientHandler sqlClientHandler = - new ArrowFlightSqlClientHandler( - "cacheKey", - sqlClient, - new ArrowFlightSqlClientHandler.Builder(), - new ArrayList<>(), - Optional.empty(), - null); + handler(sqlClient, new ArrowFlightSqlClientHandler.Builder(), trackerWithSessionOptions()); - if (shouldSuppress) { - assertDoesNotThrow(sqlClientHandler::close); - } else { - assertThrows(SQLException.class, sqlClientHandler::close); - } + assertDoesNotThrow(sqlClientHandler::close); verify(sqlClient) .closeSession( any(CloseSessionRequest.class), eq(ArrowFlightSqlClientHandler.CLOSE_SESSION_TIMEOUT)); verify(sqlClient).close(); } - private static Object[] testCloseSessionWithoutCatalog() { - return new Object[] { - new Object[] {FlightStatusCode.UNIMPLEMENTED, true}, - new Object[] {FlightStatusCode.INVALID_ARGUMENT, true}, - new Object[] {FlightStatusCode.NOT_FOUND, true}, - new Object[] {FlightStatusCode.UNAVAILABLE, true}, - new Object[] {FlightStatusCode.UNAUTHENTICATED, true}, - new Object[] {FlightStatusCode.UNKNOWN, false}, - new Object[] {FlightStatusCode.TIMED_OUT, false}, - }; + @Test + public void testCloseWithoutSessionDoesNotCloseSession() throws Exception { + FlightSqlClient sqlClient = mock(FlightSqlClient.class); + ArrowFlightSqlClientHandler sqlClientHandler = + handler(sqlClient, new ArrowFlightSqlClientHandler.Builder()); + + sqlClientHandler.close(); + + verify(sqlClient, never()) + .closeSession(any(CloseSessionRequest.class), any(CallOption[].class)); + verify(sqlClient).close(); } - private static Object[] testCloseHandlesFlightRuntimeException() { - CallStatus benignInternalError = - new CallStatus(FlightStatusCode.INTERNAL, null, "Connection closed after GOAWAY", null); - CallStatus notBenignInternalError = - new CallStatus(FlightStatusCode.INTERNAL, null, "Not a benign internal error", null); - CallStatus unavailableError = new CallStatus(FlightStatusCode.UNAVAILABLE, null, null, null); - CallStatus unknownError = new CallStatus(FlightStatusCode.UNKNOWN, null, null, null); - return new Object[] { - new Object[] {true, benignInternalError, true}, - new Object[] {false, benignInternalError, true}, - new Object[] {true, notBenignInternalError, false}, - new Object[] {false, notBenignInternalError, false}, - new Object[] {true, unavailableError, true}, - new Object[] {false, unavailableError, true}, - new Object[] {true, unknownError, false}, - new Object[] {false, unknownError, false}, - new Object[] {true, CallStatus.CANCELLED, false}, - }; + @Test + public void testCloseAfterSetCatalogClosesSession() throws Exception { + FlightSqlClient sqlClient = mock(FlightSqlClient.class); + when(sqlClient.setSessionOptions(any(SetSessionOptionsRequest.class), any(CallOption[].class))) + .thenReturn(new SetSessionOptionsResult(Collections.emptyMap())); + ArrowFlightSqlClientHandler sqlClientHandler = + handler(sqlClient, new ArrowFlightSqlClientHandler.Builder()); + + sqlClientHandler.setCatalog("test_catalog"); + sqlClientHandler.close(); + + verify(sqlClient).closeSession(any(CloseSessionRequest.class), any(CallOption[].class)); + verify(sqlClient).close(); + } + + @Test + public void testCloseAfterSessionCookieClosesSession() throws Exception { + FlightSqlClient sqlClient = mock(FlightSqlClient.class); + ServerSessionTracker sessionTracker = new ServerSessionTracker(); + CallHeaders headers = new FlightCallHeaders(); + headers.insert("Set-Cookie", "session=1"); + sessionTracker.onCallStarted(new CallInfo(FlightMethod.HANDSHAKE)).onHeadersReceived(headers); + ArrowFlightSqlClientHandler sqlClientHandler = + handler(sqlClient, new ArrowFlightSqlClientHandler.Builder(), sessionTracker); + + sqlClientHandler.close(); + + verify(sqlClient).closeSession(any(CloseSessionRequest.class), any(CallOption[].class)); + verify(sqlClient).close(); + } + + @Test + public void testHeadersWithoutCookieDoNotStartSession() { + ServerSessionTracker sessionTracker = new ServerSessionTracker(); + CallHeaders headers = new FlightCallHeaders(); + headers.insert("x-other", "value"); + sessionTracker.onCallStarted(new CallInfo(FlightMethod.HANDSHAKE)).onHeadersReceived(headers); + + assertFalse(sessionTracker.mayHaveSession()); } @Test public void testCloseFromBuilderCopyDoesNotCloseSession() throws Exception { FlightSqlClient sqlClient = mock(FlightSqlClient.class); ArrowFlightSqlClientHandler sqlClientHandler = - new ArrowFlightSqlClientHandler( - "cacheKey", + handler( sqlClient, new ArrowFlightSqlClientHandler.Builder(new ArrowFlightSqlClientHandler.Builder()), - new ArrayList<>(), - Optional.of("test_catalog"), - null); + trackerWithSessionOptions()); sqlClientHandler.close();