Skip to content

Commit

Permalink
Added Polly retry policy for establishing a database connection.
Browse files Browse the repository at this point in the history
  • Loading branch information
gmcelhanon committed Nov 11, 2024
1 parent 08157ec commit 17c8cf6
Showing 1 changed file with 18 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@
using System.Threading.Tasks;
using EdFi.Ods.Common.Database;
using EdFi.Ods.Common.Exceptions;
using log4net;
using NHibernate.Connection;
using Polly;
using Polly.Contrib.WaitAndRetry;

namespace EdFi.Ods.Common.Infrastructure.Configuration
{
Expand All @@ -19,6 +22,8 @@ public class NHibernateOdsConnectionProvider : DriverConnectionProvider

private readonly IOdsDatabaseConnectionStringProvider _connectionStringProvider;

private readonly ILog _logger = LogManager.GetLogger(typeof(NHibernateOdsConnectionProvider));

public NHibernateOdsConnectionProvider(IOdsDatabaseConnectionStringProvider connectionStringProvider)
{
_connectionStringProvider = connectionStringProvider;
Expand All @@ -32,7 +37,19 @@ public override DbConnection GetConnection()
{
connection.ConnectionString = _connectionStringProvider.GetConnectionString();

connection.Open();
// Define a retry policy with exponential backoff
var retryPolicy = Policy
.Handle<Exception>(ex => !(ex is EdFiProblemDetailsExceptionBase)) // Retry on any exception except EdFiProblemDetailsExceptionBase
.WaitAndRetry(Backoff.ExponentialBackoff(
initialDelay: TimeSpan.FromSeconds(1), // Initial retry delay
retryCount: 5),
onRetry: (exception, timeSpan, retryAttempt, context) =>
{
_logger.Warn($"Retry attempt {retryAttempt} of 5: Retrying connection in {timeSpan.TotalSeconds} seconds due to exception: {exception.Message}");
});

// Execute the Open method with the retry policy
retryPolicy.Execute(() => connection.Open());
}
catch (EdFiProblemDetailsExceptionBase)
{
Expand Down

0 comments on commit 17c8cf6

Please sign in to comment.