mirror of
https://github.com/btcpayserver/btcpayserver.git
synced 2024-11-19 18:11:36 +01:00
d5d0be5824
* Editorconfig: Add space_before_self_closing setting This was a difference between the way dotnet-format and Rider format code. See https://www.jetbrains.com/help/rider/EditorConfig_Index.html * Editorconfig: Keep 4 spaces indentation for Swagger JSON files They are all formatted that way, let's keep it like that. * Apply dotnet-format, mostly white-space related changes
71 lines
2.2 KiB
C#
71 lines
2.2 KiB
C#
using System;
|
|
using System.Data.Common;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using BTCPayServer.Configuration;
|
|
using BTCPayServer.Logging;
|
|
using Microsoft.Extensions.Configuration;
|
|
using Microsoft.Extensions.Hosting;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using Npgsql;
|
|
|
|
namespace BTCPayServer.Services
|
|
{
|
|
public class NBXplorerConnectionFactory : IHostedService
|
|
{
|
|
public NBXplorerConnectionFactory(IOptions<NBXplorerOptions> nbXplorerOptions, Logs logs)
|
|
{
|
|
connectionString = nbXplorerOptions.Value.ConnectionString;
|
|
Logs = logs;
|
|
}
|
|
string connectionString;
|
|
|
|
public bool Available { get; set; }
|
|
public Logs Logs { get; }
|
|
|
|
async Task IHostedService.StartAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (!string.IsNullOrEmpty(connectionString))
|
|
{
|
|
Available = true;
|
|
try
|
|
{
|
|
await using var conn = await OpenConnection();
|
|
Logs.Configuration.LogInformation("Connection to NBXplorer's database successful, dashboard and reporting features activated.");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new ConfigException("Error while trying to connection to explorer.postgres: " + ex.Message);
|
|
}
|
|
}
|
|
}
|
|
|
|
public async Task<DbConnection> OpenConnection()
|
|
{
|
|
int maxRetries = 10;
|
|
int retries = maxRetries;
|
|
retry:
|
|
var conn = new Npgsql.NpgsqlConnection(connectionString);
|
|
try
|
|
{
|
|
await conn.OpenAsync();
|
|
}
|
|
catch (PostgresException ex) when (ex.IsTransient && retries > 0)
|
|
{
|
|
retries--;
|
|
await conn.DisposeAsync();
|
|
await Task.Delay((maxRetries - retries) * 100);
|
|
goto retry;
|
|
}
|
|
return conn;
|
|
}
|
|
|
|
Task IHostedService.StopAsync(CancellationToken cancellationToken)
|
|
{
|
|
Npgsql.NpgsqlConnection.ClearAllPools();
|
|
return Task.CompletedTask;
|
|
}
|
|
}
|
|
}
|