51 lines
1.8 KiB
C#
51 lines
1.8 KiB
C#
using back.Options;
|
|
using healthchecks;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace back.healthchecks;
|
|
|
|
[HealthCheckExecutionOptions(retryAttempts: 2, timeout: "00:00:05", retryDelay: "00:00:01", severity: HealthCheckSeverity.Critical)]
|
|
public class SqliteHealthCheck : IHealthCheck
|
|
{
|
|
private readonly DatabaseConfig config;
|
|
public SqliteHealthCheck(IOptionsMonitor<DatabaseConfig> optionsSnapshot)
|
|
{
|
|
config = optionsSnapshot.Get(DatabaseConfig.DataStorage);
|
|
}
|
|
|
|
public Task<HealthCheckResult> CheckAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
// check if can connect to sqlite database
|
|
// then run a query to Users table to see if User.SystemUser exists
|
|
var isHealthy = false;
|
|
var details = string.Empty;
|
|
try
|
|
{
|
|
using var connection = new Microsoft.Data.Sqlite.SqliteConnection(config.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
|
|
});
|
|
}
|
|
}
|