Fix idle/busy conn. pool metrics when using NpgsqlDataSource #5497
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I've recently tried to move to
NpgsqlDataSource
to create connection on my company's codebase (moving fromnew NpgsqlConnection(connectionString)
to creating data sources at startup and then creating connections with_myDataSource.CreateConnection()
.Incidentally, I realized that the "Idle Connections" and "Busy Connections" metrics we produce for each connection pool disappeared with my change.
For more context, we're relying on
PollingCounters
inNpgsqlEventSource
to gather these metrics (link in Npgsql code).After digging into the code, I realized that the only place where
NpgsqlEventSource.DataSourceCreated()
(which adds the data sources to the list of data sources to increment these polling counters for) was called from wasNpgsqlConnection.SetupDataSource()
which itself is only called inNpgsqlConnection.ConnectionString.set
.When going through the standard
NpgsqlConnection(string)
constructor, this setter is called accordingly... but not when building the connection withNpgsqlConnection.FromDataSource()
.This PR proposes a naive fix: when instantiating a data source, register it against
NpgsqlEventSource
.In order to prevent duplicates in
NpgsqlEventSource._dataSources
, I added a duplicate check (unit tests weren't passing without this check), inNpgsqlEventSource.DataSourceCreated
.In practice, if a user register multiple data sources against the exact same ConnectionString, only metrics for the first created data source will be reported. Given that this is kind of an anti-pattern, I voluntarily didn't try to come up with anything smarter for that particular edge case.
I came across a 1-year old issue which I think has been opened for the a similar problem.
Fixes #4798