Skip to content

Commit e5f6412

Browse files
author
Zhen Li
committed
Remove optional config and always leave to users to call instead.
1 parent 1d0e2b3 commit e5f6412

23 files changed

+152
-187
lines changed

driver/src/main/java/org/neo4j/driver/Config.java

Lines changed: 0 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,6 @@ public class Config
9494
private final ServerAddressResolver resolver;
9595

9696
private final boolean isMetricsEnabled;
97-
private final boolean isConnectivityVerificationEnabledOnDriverCreation;
9897

9998
private Config( ConfigBuilder builder )
10099
{
@@ -116,7 +115,6 @@ private Config( ConfigBuilder builder )
116115
this.resolver = builder.resolver;
117116

118117
this.isMetricsEnabled = builder.isMetricsEnabled;
119-
this.isConnectivityVerificationEnabledOnDriverCreation = builder.isConnectivityVerificationEnabledOnDriverCreation;
120118
}
121119

122120
/**
@@ -295,14 +293,6 @@ public boolean isMetricsEnabled()
295293
return isMetricsEnabled;
296294
}
297295

298-
/**
299-
* @return if the connectivity verification is enabled on driver creation.
300-
*/
301-
public boolean isConnectivityVerificationEnabledOnDriverCreation()
302-
{
303-
return isConnectivityVerificationEnabledOnDriverCreation;
304-
}
305-
306296
/**
307297
* Used to build new config instances
308298
*/
@@ -323,7 +313,6 @@ public static class ConfigBuilder
323313
private RetrySettings retrySettings = RetrySettings.DEFAULT;
324314
private ServerAddressResolver resolver;
325315
private boolean isMetricsEnabled = false;
326-
private boolean isConnectivityVerificationEnabledOnDriverCreation = true;
327316

328317
private ConfigBuilder() {}
329318

@@ -803,23 +792,6 @@ public ConfigBuilder withoutDriverMetrics()
803792
return this;
804793
}
805794

806-
/**
807-
*
808-
* Enables or disables connectivity verification on the driver creation.
809-
* When it is enabled, on driver creation, such as {@link GraphDatabase#driver(String)}
810-
* the driver will try to connect to a remote server or a cluster to verify the driver can connect to the configured server or cluster.
811-
* This verification requires a network connection being established and therefore takes extra time to create the driver.
812-
*
813-
* When it is disabled, the driver will immediately without any network connection creation.
814-
* @param isEnabled enable or disable connection verification on driver creation.
815-
* @return this builder.
816-
*/
817-
public ConfigBuilder withConnectivityVerificationEnabledOnDriverCreation( boolean isEnabled )
818-
{
819-
this.isConnectivityVerificationEnabledOnDriverCreation = isEnabled;
820-
return this;
821-
}
822-
823795
/**
824796
* Create a config instance from this builder.
825797
* <p>

driver/src/main/java/org/neo4j/driver/GraphDatabase.java

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -154,19 +154,40 @@ public static Driver routingDriver( Iterable<URI> routingUris, AuthToken authTok
154154

155155
for ( URI uri : routingUris )
156156
{
157+
final Driver driver = driver( uri, authToken, config );
157158
try
158159
{
159-
return driver( uri, authToken, config );
160+
driver.verifyConnectivity();
161+
return driver;
160162
}
161163
catch ( ServiceUnavailableException e )
162164
{
163165
log.warn( "Unable to create routing driver for URI: " + uri, e );
166+
closeDriver( driver, uri, log );
167+
}
168+
catch ( Throwable e )
169+
{
170+
// for any other errors, we first close the driver and then rethrow the original error out.
171+
closeDriver( driver, uri, log );
172+
throw e;
164173
}
165174
}
166175

167176
throw new ServiceUnavailableException( "Failed to discover an available server" );
168177
}
169178

179+
private static void closeDriver( Driver driver, URI uri, Logger log )
180+
{
181+
try
182+
{
183+
driver.close();
184+
}
185+
catch ( Throwable closeError )
186+
{
187+
log.warn( "Unable to close driver towards URI: " + uri, closeError );
188+
}
189+
}
190+
170191
private static void assertRoutingUris( Iterable<URI> uris )
171192
{
172193
for ( URI uri : uris )

driver/src/main/java/org/neo4j/driver/internal/DriverFactory.java

Lines changed: 9 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,13 @@
2727
import java.net.URI;
2828
import java.security.GeneralSecurityException;
2929

30+
import org.neo4j.driver.AuthToken;
31+
import org.neo4j.driver.AuthTokens;
32+
import org.neo4j.driver.Config;
33+
import org.neo4j.driver.Driver;
34+
import org.neo4j.driver.Logger;
35+
import org.neo4j.driver.Logging;
36+
import org.neo4j.driver.exceptions.ClientException;
3037
import org.neo4j.driver.internal.async.connection.BootstrapFactory;
3138
import org.neo4j.driver.internal.async.connection.ChannelConnector;
3239
import org.neo4j.driver.internal.async.connection.ChannelConnectorImpl;
@@ -49,19 +56,11 @@
4956
import org.neo4j.driver.internal.spi.ConnectionProvider;
5057
import org.neo4j.driver.internal.util.Clock;
5158
import org.neo4j.driver.internal.util.Futures;
52-
import org.neo4j.driver.AuthToken;
53-
import org.neo4j.driver.AuthTokens;
54-
import org.neo4j.driver.Config;
55-
import org.neo4j.driver.Driver;
56-
import org.neo4j.driver.Logger;
57-
import org.neo4j.driver.Logging;
58-
import org.neo4j.driver.exceptions.ClientException;
59-
import org.neo4j.driver.exceptions.ServiceUnavailableException;
6059
import org.neo4j.driver.net.ServerAddressResolver;
6160

6261
import static java.lang.String.format;
63-
import static org.neo4j.driver.internal.metrics.MetricsProvider.METRICS_DISABLED_PROVIDER;
6462
import static org.neo4j.driver.internal.cluster.IdentityResolver.IDENTITY_RESOLVER;
63+
import static org.neo4j.driver.internal.metrics.MetricsProvider.METRICS_DISABLED_PROVIDER;
6564
import static org.neo4j.driver.internal.security.SecurityPlan.insecure;
6665
import static org.neo4j.driver.internal.util.ErrorUtil.addSuppressed;
6766

@@ -105,14 +104,7 @@ public final Driver newInstance ( URI uri, AuthToken authToken, RoutingSettings
105104
MetricsProvider metricsProvider = createDriverMetrics( config, createClock() );
106105
ConnectionPool connectionPool = createConnectionPool( authToken, securityPlan, bootstrap, metricsProvider, config, ownsEventLoopGroup );
107106

108-
InternalDriver driver = createDriver( uri, securityPlan, address, connectionPool, eventExecutorGroup, newRoutingSettings, retryLogic, metricsProvider, config );
109-
110-
if( config.isConnectivityVerificationEnabledOnDriverCreation() )
111-
{
112-
verifyConnectivity( driver, connectionPool, config );
113-
}
114-
115-
return driver;
107+
return createDriver( uri, securityPlan, address, connectionPool, eventExecutorGroup, newRoutingSettings, retryLogic, metricsProvider, config );
116108
}
117109

118110
protected ConnectionPool createConnectionPool( AuthToken authToken, SecurityPlan securityPlan, Bootstrap bootstrap,
@@ -369,30 +361,6 @@ private static void assertNoRoutingContext( URI uri, RoutingSettings routingSett
369361
}
370362
}
371363

372-
private static void verifyConnectivity( InternalDriver driver, ConnectionPool connectionPool, Config config )
373-
{
374-
try
375-
{
376-
// block to verify connectivity, close connection pool if thread gets interrupted
377-
Futures.blockingGet( driver.verifyConnectivityAsync(),
378-
() -> closeConnectionPoolOnThreadInterrupt( connectionPool, config.logging() ) );
379-
}
380-
catch ( Throwable connectionError )
381-
{
382-
if ( Thread.currentThread().isInterrupted() )
383-
{
384-
// current thread has been interrupted while verifying connectivity
385-
// connection pool should've been closed
386-
throw new ServiceUnavailableException( "Unable to create driver. Thread has been interrupted.",
387-
connectionError );
388-
}
389-
390-
// we need to close the connection pool if driver creation threw exception
391-
closeConnectionPoolAndSuppressError( connectionPool, connectionError );
392-
throw connectionError;
393-
}
394-
}
395-
396364
private static void closeConnectionPoolAndSuppressError( ConnectionPool connectionPool, Throwable mainError )
397365
{
398366
try
@@ -404,11 +372,4 @@ private static void closeConnectionPoolAndSuppressError( ConnectionPool connecti
404372
addSuppressed( mainError, closeError );
405373
}
406374
}
407-
408-
private static void closeConnectionPoolOnThreadInterrupt( ConnectionPool pool, Logging logging )
409-
{
410-
Logger log = logging.getLog( Driver.class.getSimpleName() );
411-
log.warn( "Driver creation interrupted while verifying connectivity. Connection pool will be closed" );
412-
pool.close();
413-
}
414375
}

driver/src/test/java/org/neo4j/driver/GraphDatabaseTest.java

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ void boltSchemeShouldInstantiateDirectDriver() throws Exception
6060

6161
// When
6262
Driver driver = GraphDatabase.driver( uri, INSECURE_CONFIG );
63+
driver.verifyConnectivity();
6364

6465
// Then
6566
assertThat( driver, is( directDriver() ) );
@@ -78,6 +79,7 @@ void boltPlusDiscoverySchemeShouldInstantiateClusterDriver() throws Exception
7879

7980
// When
8081
Driver driver = GraphDatabase.driver( uri, INSECURE_CONFIG );
82+
driver.verifyConnectivity();
8183

8284
// Then
8385
assertThat( driver, is( clusterDriver() ) );
@@ -146,9 +148,10 @@ void shouldRespondToInterruptsWhenConnectingToUnresponsiveServer() throws Except
146148
// setup other thread to interrupt current thread when it blocks
147149
TestUtil.interruptWhenInWaitingState( Thread.currentThread() );
148150

151+
final Driver driver = GraphDatabase.driver( "bolt://localhost:" + serverSocket.getLocalPort() );
149152
try
150153
{
151-
assertThrows( ServiceUnavailableException.class, () -> GraphDatabase.driver( "bolt://localhost:" + serverSocket.getLocalPort() ) );
154+
assertThrows( ServiceUnavailableException.class, driver::verifyConnectivity );
152155
}
153156
finally
154157
{
@@ -176,9 +179,9 @@ private static void testFailureWhenServerDoesNotRespond( boolean encrypted ) thr
176179
{
177180
int connectionTimeoutMillis = 1_000;
178181
Config config = createConfig( encrypted, connectionTimeoutMillis );
182+
final Driver driver = GraphDatabase.driver( URI.create( "bolt://localhost:" + server.getLocalPort() ), config );
179183

180-
ServiceUnavailableException e = assertThrows( ServiceUnavailableException.class,
181-
() -> GraphDatabase.driver( URI.create( "bolt://localhost:" + server.getLocalPort() ), config ) );
184+
ServiceUnavailableException e = assertThrows( ServiceUnavailableException.class, driver::verifyConnectivity );
182185
assertEquals( e.getMessage(), "Unable to establish connection in " + connectionTimeoutMillis + "ms" );
183186
}
184187
}

driver/src/test/java/org/neo4j/driver/integration/CredentialsIT.java

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,11 +81,11 @@ void shouldBePossibleToChangePassword() throws Exception
8181
}
8282

8383
// verify old password does not work
84-
assertThrows( AuthenticationException.class,
85-
() -> GraphDatabase.driver( neo4j.uri(), AuthTokens.basic( "neo4j", PASSWORD ) ) );
84+
final Driver badDriver = GraphDatabase.driver( CredentialsIT.neo4j.uri(), basic( "neo4j", PASSWORD ) );
85+
assertThrows( AuthenticationException.class, badDriver::verifyConnectivity );
8686

8787
// verify new password works
88-
try ( Driver driver = GraphDatabase.driver( neo4j.uri(), AuthTokens.basic( "neo4j", newPassword ) );
88+
try ( Driver driver = GraphDatabase.driver( CredentialsIT.neo4j.uri(), AuthTokens.basic( "neo4j", newPassword ) );
8989
Session session = driver.session() )
9090
{
9191
session.run( "RETURN 2" ).consume();
@@ -177,6 +177,7 @@ private void testDriverFailureOnWrongCredentials( String uri )
177177
Config config = Config.builder().withLogging( DEV_NULL_LOGGING ).build();
178178
AuthToken authToken = AuthTokens.basic( "neo4j", "wrongSecret" );
179179

180-
assertThrows( AuthenticationException.class, () -> GraphDatabase.driver( uri, authToken, config ) );
180+
final Driver driver = GraphDatabase.driver( uri, authToken, config );
181+
assertThrows( AuthenticationException.class, driver::verifyConnectivity );
181182
}
182183
}

driver/src/test/java/org/neo4j/driver/integration/EncryptionIT.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ private void testMismatchingEncryption( BoltTlsLevel tlsLevel, boolean driverEnc
119119
Config config = newConfig( driverEncrypted );
120120

121121
RuntimeException e = assertThrows( RuntimeException.class,
122-
() -> GraphDatabase.driver( neo4j.uri(), neo4j.authToken(), config ).close() );
122+
() -> GraphDatabase.driver( neo4j.uri(), neo4j.authToken(), config ).verifyConnectivity() );
123123

124124
// pre 3.1 neo4j throws different exception when encryption required but not used
125125
if ( neo4jVersion.lessThan( v3_1_0 ) && tlsLevel == BoltTlsLevel.REQUIRED )

driver/src/test/java/org/neo4j/driver/integration/ErrorIT.java

Lines changed: 29 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -33,13 +33,6 @@
3333
import java.util.function.Consumer;
3434
import java.util.stream.Stream;
3535

36-
import org.neo4j.driver.internal.cluster.RoutingSettings;
37-
import org.neo4j.driver.internal.messaging.response.FailureMessage;
38-
import org.neo4j.driver.internal.retry.RetrySettings;
39-
import org.neo4j.driver.internal.util.io.ChannelTrackingDriverFactory;
40-
import org.neo4j.driver.internal.util.io.ChannelTrackingDriverFactoryWithFailingMessageFormat;
41-
import org.neo4j.driver.internal.util.FailingMessageFormat;
42-
import org.neo4j.driver.internal.util.FakeClock;
4336
import org.neo4j.driver.AuthToken;
4437
import org.neo4j.driver.Config;
4538
import org.neo4j.driver.Driver;
@@ -49,6 +42,13 @@
4942
import org.neo4j.driver.Transaction;
5043
import org.neo4j.driver.exceptions.ClientException;
5144
import org.neo4j.driver.exceptions.ServiceUnavailableException;
45+
import org.neo4j.driver.internal.cluster.RoutingSettings;
46+
import org.neo4j.driver.internal.messaging.response.FailureMessage;
47+
import org.neo4j.driver.internal.retry.RetrySettings;
48+
import org.neo4j.driver.internal.util.FailingMessageFormat;
49+
import org.neo4j.driver.internal.util.FakeClock;
50+
import org.neo4j.driver.internal.util.io.ChannelTrackingDriverFactory;
51+
import org.neo4j.driver.internal.util.io.ChannelTrackingDriverFactoryWithFailingMessageFormat;
5252
import org.neo4j.driver.util.ParallelizableIT;
5353
import org.neo4j.driver.util.SessionExtension;
5454

@@ -143,7 +143,8 @@ void shouldAllowNewTransactionAfterRecoverableError()
143143
@Test
144144
void shouldExplainConnectionError()
145145
{
146-
ServiceUnavailableException e = assertThrows( ServiceUnavailableException.class, () -> GraphDatabase.driver( "bolt://localhost:7777" ) );
146+
final Driver driver = GraphDatabase.driver( "bolt://localhost:7777" );
147+
ServiceUnavailableException e = assertThrows( ServiceUnavailableException.class, driver::verifyConnectivity );
147148

148149
assertEquals( "Unable to connect to localhost:7777, ensure the database is running " +
149150
"and that there is a working network connection to it.", e.getMessage() );
@@ -179,7 +180,8 @@ void shouldGetHelpfulErrorWhenTryingToConnectToHttpPort() throws Throwable
179180

180181
Config config = Config.builder().withoutEncryption().build();
181182

182-
ClientException e = assertThrows( ClientException.class, () -> GraphDatabase.driver( "bolt://localhost:" + session.httpPort(), config ) );
183+
final Driver driver = GraphDatabase.driver( "bolt://localhost:" + session.httpPort(), config );
184+
ClientException e = assertThrows( ClientException.class, driver::verifyConnectivity );
183185
assertEquals( "Server responded HTTP. Make sure you are not trying to connect to the http endpoint " +
184186
"(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)", e.getMessage() );
185187
}
@@ -264,25 +266,29 @@ private Throwable testChannelErrorHandling( Consumer<FailingMessageFormat> messa
264266
Config config = Config.builder().withLogging( DEV_NULL_LOGGING ).build();
265267
Throwable queryError = null;
266268

267-
try ( Driver driver = driverFactory.newInstance( uri, authToken, routingSettings, retrySettings, config );
268-
Session session = driver.session() )
269+
try ( Driver driver = driverFactory.newInstance( uri, authToken, routingSettings, retrySettings, config ) )
269270
{
270-
messageFormatSetup.accept( driverFactory.getFailingMessageFormat() );
271-
272-
try
271+
driver.verifyConnectivity();
272+
try(Session session = driver.session() )
273273
{
274-
session.run( "RETURN 1" ).consume();
275-
fail( "Exception expected" );
274+
messageFormatSetup.accept( driverFactory.getFailingMessageFormat() );
275+
276+
try
277+
{
278+
session.run( "RETURN 1" ).consume();
279+
fail( "Exception expected" );
280+
}
281+
catch ( Throwable error )
282+
{
283+
queryError = error;
284+
}
285+
286+
assertSingleChannelIsClosed( driverFactory );
287+
assertNewQueryCanBeExecuted( session, driverFactory );
276288
}
277-
catch ( Throwable error )
278-
{
279-
queryError = error;
280-
}
281-
282-
assertSingleChannelIsClosed( driverFactory );
283-
assertNewQueryCanBeExecuted( session, driverFactory );
284289
}
285290

291+
286292
return queryError;
287293
}
288294

0 commit comments

Comments
 (0)