-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDbCheck.cs
74 lines (61 loc) · 2.52 KB
/
DbCheck.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using BusinessCard.Infrastructure;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace BusinessCard
{
public class DbCheck : IHealthCheck
{
private readonly Ctx _ctx;
public DbCheck(Ctx ctx)
{
_ctx = ctx;
}
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
CancellationToken cancellationToken = new CancellationToken())
{
bool canConnect = false;
Exception? exception = null;
string? description = null;
var data = new Dictionary<string, object>();
try
{
canConnect = await _ctx.Database.CanConnectAsync(cancellationToken);
data["CanConnect"] = true;
await _ctx.Database.OpenConnectionAsync(cancellationToken: cancellationToken);
data["CanOpenConnection"] = true;
await _ctx.Database.CloseConnectionAsync();
data["CanCloseConnection"] = true;
await _ctx.People.ToListAsync(cancellationToken: cancellationToken);
data["CanRead"] = true;
description = canConnect ? "Database exists" : "Database does not exist";
}
catch (Exception e)
{
exception = e;
description = $"Database existence check failed: {e.Message}";
}
return new HealthCheckResult(canConnect ? HealthStatus.Healthy : HealthStatus.Unhealthy, description,
exception, data);
}
}
public class SeedCheck : IHealthCheck
{
public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context,
CancellationToken cancellationToken = new CancellationToken())
{
var status = Seeder.Result.Status == Seeder.Status.Success ? HealthStatus.Healthy : HealthStatus.Unhealthy;
var description = Seeder.Result.Status switch
{
Seeder.Status.Success => "Seed succeeded",
Seeder.Status.NoRun => "Seed not run",
_ => "Seed failed: " + Seeder.Result.Exception?.Message
};
var result = new HealthCheckResult(status, description, Seeder.Result.Exception);
return Task.FromResult(result);
}
}
}