From e89211e7f60fd6b5ec94be643c8d8fffcec5d0d7 Mon Sep 17 00:00:00 2001
From: Ash Davies <3853061+DrizzlyOwl@users.noreply.github.com>
Date: Mon, 9 Dec 2024 10:16:33 +0000
Subject: [PATCH] Add DbContextChecks to Health Checks (#648)
This will ensure that the /healthcheck endpoint correctly reports the status of the service if a database connection faults
---
.../Dfe.Academies.Infrastructure.csproj | 1 +
...frastructureServiceCollectionExtensions.cs | 11 +++-
PersonsApi/PersonsApi.csproj | 2 +-
PersonsApi/Program.cs | 2 +
PersonsApi/Startup.cs | 5 +-
.../Controllers/HealthCheckController.cs | 62 -------------------
TramsDataApi/Program.cs | 2 +
7 files changed, 18 insertions(+), 67 deletions(-)
delete mode 100644 TramsDataApi/Controllers/HealthCheckController.cs
diff --git a/Dfe.Academies.Api.Infrastructure/Dfe.Academies.Infrastructure.csproj b/Dfe.Academies.Api.Infrastructure/Dfe.Academies.Infrastructure.csproj
index 2dfff1496..9d3970641 100644
--- a/Dfe.Academies.Api.Infrastructure/Dfe.Academies.Infrastructure.csproj
+++ b/Dfe.Academies.Api.Infrastructure/Dfe.Academies.Infrastructure.csproj
@@ -17,6 +17,7 @@
+
diff --git a/Dfe.Academies.Api.Infrastructure/InfrastructureServiceCollectionExtensions.cs b/Dfe.Academies.Api.Infrastructure/InfrastructureServiceCollectionExtensions.cs
index 44ff4a9be..3c3c5cbe7 100644
--- a/Dfe.Academies.Api.Infrastructure/InfrastructureServiceCollectionExtensions.cs
+++ b/Dfe.Academies.Api.Infrastructure/InfrastructureServiceCollectionExtensions.cs
@@ -31,6 +31,8 @@ public static IServiceCollection AddInfrastructureDependencyGroup(
services.AddDbContext(options =>
options.UseSqlServer(connectionString));
+ AddInfrastructureHealthChecks(services);
+
return services;
}
@@ -58,10 +60,17 @@ public static IServiceCollection AddPersonsApiInfrastructureDependencyGroup(
services.AddDbContext(options =>
options.UseSqlServer(connectionString));
+ AddInfrastructureHealthChecks(services);
+
// Authentication
services.AddCustomAuthorization(config);
return services;
}
+
+ public static void AddInfrastructureHealthChecks(this IServiceCollection services) {
+ services.AddHealthChecks()
+ .AddDbContextCheck("Academies Database");
+ }
}
-}
\ No newline at end of file
+}
diff --git a/PersonsApi/PersonsApi.csproj b/PersonsApi/PersonsApi.csproj
index 461f8beca..a2d366656 100644
--- a/PersonsApi/PersonsApi.csproj
+++ b/PersonsApi/PersonsApi.csproj
@@ -62,5 +62,5 @@
-
+
diff --git a/PersonsApi/Program.cs b/PersonsApi/Program.cs
index cfd31fa8b..4a1eeccb9 100644
--- a/PersonsApi/Program.cs
+++ b/PersonsApi/Program.cs
@@ -30,4 +30,6 @@
logger.LogInformation("Logger is working...");
+app.MapHealthChecks("/HealthCheck").AllowAnonymous();
+
app.Run();
diff --git a/PersonsApi/Startup.cs b/PersonsApi/Startup.cs
index 2c222d88d..a57fd492f 100644
--- a/PersonsApi/Startup.cs
+++ b/PersonsApi/Startup.cs
@@ -99,7 +99,6 @@ public void ConfigureServices(IServiceCollection services)
{
configure.Title = "PersonsApi";
});
-
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
@@ -175,10 +174,10 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IApiVers
app.UseHttpsRedirection();
app.UseRouting();
- app.UseAuthentication();
+ app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
-}
\ No newline at end of file
+}
diff --git a/TramsDataApi/Controllers/HealthCheckController.cs b/TramsDataApi/Controllers/HealthCheckController.cs
deleted file mode 100644
index 917017e8b..000000000
--- a/TramsDataApi/Controllers/HealthCheckController.cs
+++ /dev/null
@@ -1,62 +0,0 @@
-using System.IO;
-using Microsoft.AspNetCore.Mvc;
-using Microsoft.Data.SqlClient;
-using Microsoft.Extensions.Logging;
-using TramsDataApi.DatabaseModels;
-using Swashbuckle.AspNetCore.Annotations;
-
-namespace TramsDataApi.Controllers
-{
- ///
- /// Provides endpoints for checking the health of the API and database.
- ///
- [ApiController]
- [Route("[controller]")]
- [ApiVersion("1.0")]
- [SwaggerTag("Health Check Endpoints")]
- public class HealthCheckController : ControllerBase
- {
- private readonly LegacyTramsDbContext _dbContext;
- private readonly ILogger _logger;
-
- ///
- /// Constructor that initializes database and logger.
- ///
- /// Database context.
- /// Logging service.
- public HealthCheckController(LegacyTramsDbContext context, ILogger logger)
- {
- _dbContext = context;
- _logger = logger;
- }
-
- ///
- /// Provides a basic health check for the API.
- ///
- /// String message indicating health status.
- [HttpGet]
- [HttpHead]
- [SwaggerOperation(Summary = "Performs a basic health check", Description = "Checks if the API is operational.")]
- [SwaggerResponse(200, "API is healthy.")]
- public string Get()
- {
- _logger.LogInformation("Returning OK Health Check");
- return "Health check ok";
- }
-
- ///
- /// Checks the database connectivity.
- ///
- /// Boolean indicating whether the database can be connected to.
- [HttpGet]
- [HttpHead]
- [Route("/check_db")]
- [SwaggerOperation(Summary = "Performs a database health check", Description = "Checks if the database is reachable.")]
- [SwaggerResponse(200, "Database is healthy.")]
- public bool CheckDbConnection()
- {
- _logger.LogInformation("Returning Database Health Check");
- return _dbContext.Database.CanConnect();
- }
- }
-}
diff --git a/TramsDataApi/Program.cs b/TramsDataApi/Program.cs
index 5e898a1b6..d8184ca03 100644
--- a/TramsDataApi/Program.cs
+++ b/TramsDataApi/Program.cs
@@ -37,4 +37,6 @@
logger.LogInformation("Logger is working...");
+app.MapHealthChecks("/HealthCheck").AllowAnonymous();
+
app.Run();