53 lines
2.2 KiB
C#
53 lines
2.2 KiB
C#
using back.Options;
|
|
using healthchecks;
|
|
using healthchecks.Abstracts;
|
|
using back.healthchecks.Options;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace back.healthchecks;
|
|
|
|
public class SqliteHealthCheck(IOptionsMonitor<DatabaseConfig> databaseConfig, IOptionsMonitor<HealthChecksConfigs> healthchecksConfig) : IHealthCheck
|
|
{
|
|
private readonly DatabaseConfig databaseConfig = databaseConfig.Get(DatabaseConfig.DataStorage);
|
|
private readonly HealthChecksConfigs hcConfig = healthchecksConfig.Get(HealthChecksConfigs.Sqlite);
|
|
|
|
public string Description => "Conecta con la base de datos SQLite y trata de hacer una consulta sobre la tabla Users.";
|
|
public int? RetryAttempts => hcConfig.RetryAttempts ?? 2;
|
|
public TimeSpan? Timeout => hcConfig.Timeout ?? TimeSpan.FromSeconds(5);
|
|
public TimeSpan? RetryDelay => hcConfig.RetryDelay ?? TimeSpan.FromSeconds(1);
|
|
public HealthCheckSeverity? Severity => hcConfig.Severity ?? HealthCheckSeverity.Critical;
|
|
|
|
public Task<HealthCheckResult> CheckAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
var isHealthy = false;
|
|
var details = string.Empty;
|
|
try
|
|
{
|
|
using var connection = new Microsoft.Data.Sqlite.SqliteConnection(databaseConfig.ConnectionString);
|
|
connection.Open();
|
|
using var command = connection.CreateCommand();
|
|
command.CommandText = $"SELECT COUNT(1) FROM Users WHERE Id = '{DataModels.User.SystemUserId}';";
|
|
var result = command.ExecuteScalar();
|
|
if (result != null && Convert.ToInt32(result) == 1)
|
|
{
|
|
isHealthy = true;
|
|
details = "Connection to SQLite database successful and SystemUser exists.";
|
|
}
|
|
else
|
|
{
|
|
details = "Connection to SQLite database successful but SystemUser does not exist.";
|
|
}
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
details = $"Failed to connect to SQLite database: {ex.Message}";
|
|
}
|
|
|
|
return Task.FromResult(new HealthCheckResult(isHealthy, null)
|
|
{
|
|
Details = details,
|
|
Severity = isHealthy ? HealthCheckSeverity.Info : HealthCheckSeverity.Critical
|
|
});
|
|
}
|
|
}
|