Skip to content

Commit

Permalink
Populate Connection Context with DataSource
Browse files Browse the repository at this point in the history
Ensure the datasource is populated in the connection context even when
`getConnection` fails.
For instance, this datasource is used by `HikariJdbcObservationFilter`.
If the datasource is not populated, the filter fails with a NPE.

This commit guarantees that the datasource is populated in the
connection context when `getConnection` fails.

Closes #44
  • Loading branch information
ttddyy committed Jul 2, 2024
1 parent 0fd2f77 commit 92373a6
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,14 @@ private void handleGetConnectionAfter(MethodExecutionContext executionContext) {
Connection connection = (Connection) executionContext.getResult();
Observation.Scope scopeToUse = executionContext.getCustomValue(Observation.Scope.class.getName(),
Observation.Scope.class);
ConnectionContext connectionContext = executionContext.getCustomValue(ConnectionContext.class.getName(),
ConnectionContext.class);

if (connection == null) {
// Handle closing the observation due to an error from getConnection().
// Logic when getConnection failed.
// Populate the context with available info. (see gh-44)
connectionContext.setDataSource(dataSource);
// Handle closing the observation.
// For normal case, observation is stopped when connection is closed.
// see "handleConnectionClose()".
if (scopeToUse != null) {
Expand All @@ -273,8 +278,6 @@ private void handleGetConnectionAfter(MethodExecutionContext executionContext) {

String connectionId = connectionInfo.getConnectionId();
this.connectionAttributesManager.put(connectionId, connectionAttributes);
ConnectionContext connectionContext = executionContext.getCustomValue(ConnectionContext.class.getName(),
ConnectionContext.class);
populateFromConnectionAttributes(connectionContext, connectionId);

// When "getConnection" was successful, a connection is acquired.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,13 @@ void connection() throws Exception {
@Test
void getConnectionFailure() throws Exception {
this.registry.observationConfig().observationHandler(new ConnectionTracingObservationHandler(this.tracer));
// gh-44: make sure datasource is available in observation filter
this.registry.observationConfig().observationFilter((context) -> {
DataSource ds = ((DataSourceBaseContext) context).getDataSource();
assertThat(ds).as("datasource needs to be available in observation filter").isNotNull();
return context;
});

Method getConnection = DataSource.class.getMethod("getConnection");
RuntimeException exception = new RuntimeException();

Expand Down

0 comments on commit 92373a6

Please sign in to comment.