btcpayserver/BTCPayServer/Services/NBXplorerConnectionFactory.cs
d11n 7ec978fcdb
Dashboard (#3530)
* Add dashboard and chart basics

* More widgets

* Make widgets responsive

* Layout dashboard

* Prepare ExplorerClient

* Switch to Chartist

* Dynamic data for store numbers and recent transactions tiles

* Dynamic data for recent invoices tile

* Improvements

* Plug NBXPlorer DB

* Properly filter by code

* Reorder cheat mode button

* AJAX update for graph data

* Fix create invoice button

* Retry connection on transient issues

* App Top Items stats

* Design updates

* App Sales stats

* Add points for weekly histogram, set last point to current balance

Co-authored-by: nicolas.dorier <nicolas.dorier@gmail.com>
2022-04-12 16:55:10 +09:00

71 lines
2.2 KiB
C#

using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using BTCPayServer.Configuration;
using Microsoft.Extensions.Options;
using System.Data.Common;
using System;
using BTCPayServer.Logging;
using Microsoft.Extensions.Logging;
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;
}
}
}