All checks were successful
BCards Deployment Pipeline / Run Tests (push) Successful in 1s
BCards Deployment Pipeline / PR Validation (push) Has been skipped
BCards Deployment Pipeline / Build and Push Image (push) Successful in 15m39s
BCards Deployment Pipeline / Deploy to Production (ARM - OCI) (push) Successful in 1m17s
BCards Deployment Pipeline / Deploy to Staging (x86 - Local) (push) Has been skipped
BCards Deployment Pipeline / Cleanup Old Resources (push) Has been skipped
BCards Deployment Pipeline / Deployment Summary (push) Successful in 0s
73 lines
2.6 KiB
C#
73 lines
2.6 KiB
C#
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
|
using MongoDB.Driver;
|
|
using MongoDB.Bson;
|
|
using System.Diagnostics;
|
|
|
|
namespace BCards.Web.HealthChecks;
|
|
|
|
public class MongoDbHealthCheck : IHealthCheck
|
|
{
|
|
private readonly IMongoDatabase _database;
|
|
private readonly ILogger<MongoDbHealthCheck> _logger;
|
|
|
|
public MongoDbHealthCheck(IMongoDatabase database, ILogger<MongoDbHealthCheck> logger)
|
|
{
|
|
_database = database;
|
|
_logger = logger;
|
|
}
|
|
|
|
public async Task<HealthCheckResult> CheckHealthAsync(
|
|
HealthCheckContext context,
|
|
CancellationToken cancellationToken = default)
|
|
{
|
|
var stopwatch = Stopwatch.StartNew();
|
|
|
|
try
|
|
{
|
|
// Executa ping no MongoDB
|
|
var command = new BsonDocument("ping", 1);
|
|
await _database.RunCommandAsync<BsonDocument>(command, cancellationToken: cancellationToken);
|
|
|
|
stopwatch.Stop();
|
|
var duration = stopwatch.ElapsedMilliseconds;
|
|
|
|
_logger.LogInformation("MongoDB health check completed successfully in {Duration}ms", duration);
|
|
|
|
var data = new Dictionary<string, object>
|
|
{
|
|
{ "status", "healthy" },
|
|
{ "duration", $"{duration}ms" },
|
|
{ "database", _database.DatabaseNamespace.DatabaseName },
|
|
{ "connection_state", "connected" },
|
|
{ "latency", duration }
|
|
};
|
|
|
|
// Status baseado na latência
|
|
if (duration > 5000) // > 5s
|
|
return HealthCheckResult.Unhealthy($"MongoDB response time too high: {duration}ms", data: data);
|
|
|
|
if (duration > 2000) // > 2s
|
|
return HealthCheckResult.Degraded($"MongoDB response time elevated: {duration}ms", data: data);
|
|
|
|
return HealthCheckResult.Healthy($"MongoDB is responsive ({duration}ms)", data: data);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
stopwatch.Stop();
|
|
var duration = stopwatch.ElapsedMilliseconds;
|
|
|
|
_logger.LogError(ex, "MongoDB health check failed after {Duration}ms", duration);
|
|
|
|
var data = new Dictionary<string, object>
|
|
{
|
|
{ "status", "unhealthy" },
|
|
{ "duration", $"{duration}ms" },
|
|
{ "database", _database.DatabaseNamespace.DatabaseName },
|
|
{ "connection_state", "disconnected" },
|
|
{ "error", ex.Message }
|
|
};
|
|
|
|
return HealthCheckResult.Unhealthy($"MongoDB connection failed: {ex.Message}", ex, data);
|
|
}
|
|
}
|
|
} |