-
Notifications
You must be signed in to change notification settings - Fork 797
/
NpgSqlHealthCheck.cs
46 lines (39 loc) · 1.65 KB
/
NpgSqlHealthCheck.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System.Diagnostics;
using Microsoft.Extensions.Diagnostics.HealthChecks;
using Npgsql;
namespace HealthChecks.NpgSql;
/// <summary>
/// A health check for Postgres databases.
/// </summary>
public class NpgSqlHealthCheck : IHealthCheck
{
private readonly NpgSqlHealthCheckOptions _options;
public NpgSqlHealthCheck(NpgSqlHealthCheckOptions options)
{
Debug.Assert(options.ConnectionString is not null || options.DataSource is not null);
Guard.ThrowIfNull(options.CommandText, true);
_options = options;
}
/// <inheritdoc />
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
await using var connection = _options.DataSource is not null
? _options.DataSource.CreateConnection()
: new NpgsqlConnection(_options.ConnectionString);
_options.Configure?.Invoke(connection);
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
using var command = connection.CreateCommand();
command.CommandText = _options.CommandText;
var result = await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);
return _options.HealthCheckResultBuilder == null
? HealthCheckResult.Healthy()
: _options.HealthCheckResultBuilder(result);
}
catch (Exception ex)
{
return new HealthCheckResult(context.Registration.FailureStatus, description: ex.Message, exception: ex);
}
}
}