From 30e97081780a57d1698dc75da20eb470af1ddcc7 Mon Sep 17 00:00:00 2001 From: Ash Davies <3853061+DrizzlyOwl@users.noreply.github.com> Date: Thu, 5 Dec 2024 14:55:07 +0000 Subject: [PATCH] Add DbContextChecks to Health Checks This will ensure that the /healthcheck endpoint correctly reports the status of the service if a database connection faults --- PersonsApi/PersonsApi.csproj | 1 + PersonsApi/Program.cs | 2 + PersonsApi/Setup/HealthCheckSetup.cs | 16 +++++ PersonsApi/Startup.cs | 7 ++- .../Controllers/HealthCheckController.cs | 62 ------------------- TramsDataApi/Program.cs | 2 + TramsDataApi/Setup/HealthCheckSetup.cs | 17 +++++ TramsDataApi/Startup.cs | 5 ++ TramsDataApi/TramsDataApi.csproj | 1 + 9 files changed, 49 insertions(+), 64 deletions(-) create mode 100644 PersonsApi/Setup/HealthCheckSetup.cs delete mode 100644 TramsDataApi/Controllers/HealthCheckController.cs create mode 100644 TramsDataApi/Setup/HealthCheckSetup.cs diff --git a/PersonsApi/PersonsApi.csproj b/PersonsApi/PersonsApi.csproj index 461f8bec..b773af74 100644 --- a/PersonsApi/PersonsApi.csproj +++ b/PersonsApi/PersonsApi.csproj @@ -24,6 +24,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/PersonsApi/Program.cs b/PersonsApi/Program.cs index cfd31fa8..4a1eeccb 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/Setup/HealthCheckSetup.cs b/PersonsApi/Setup/HealthCheckSetup.cs new file mode 100644 index 00000000..72d9675d --- /dev/null +++ b/PersonsApi/Setup/HealthCheckSetup.cs @@ -0,0 +1,16 @@ +using Dfe.Academies.Infrastructure; + +namespace PersonsApi.Setup; + +public static class HealthCheckSetup +{ + public static void AddHealthChecks(IServiceCollection services) { + services.AddHealthChecks(); + AddDbHealthChecks(services); + } + + public static void AddDbHealthChecks(IServiceCollection services) { + services.AddHealthChecks() + .AddDbContextCheck("Academies Database"); + } +} diff --git a/PersonsApi/Startup.cs b/PersonsApi/Startup.cs index 2c222d88..6cbfa1b1 100644 --- a/PersonsApi/Startup.cs +++ b/PersonsApi/Startup.cs @@ -6,6 +6,7 @@ using Microsoft.FeatureManagement; using NetEscapades.AspNetCore.SecurityHeaders; using PersonsApi.Middleware; +using PersonsApi.Setup; using PersonsApi.Swagger; using Swashbuckle.AspNetCore.SwaggerUI; using System.Reflection; @@ -100,6 +101,8 @@ public void ConfigureServices(IServiceCollection services) configure.Title = "PersonsApi"; }); + // Register Health Checks + HealthCheckSetup.AddHealthChecks(services); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. @@ -175,10 +178,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 917017e8..00000000 --- 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 5e898a1b..d8184ca0 100644 --- a/TramsDataApi/Program.cs +++ b/TramsDataApi/Program.cs @@ -37,4 +37,6 @@ logger.LogInformation("Logger is working..."); +app.MapHealthChecks("/HealthCheck").AllowAnonymous(); + app.Run(); diff --git a/TramsDataApi/Setup/HealthCheckSetup.cs b/TramsDataApi/Setup/HealthCheckSetup.cs new file mode 100644 index 00000000..558c42df --- /dev/null +++ b/TramsDataApi/Setup/HealthCheckSetup.cs @@ -0,0 +1,17 @@ +using Microsoft.Extensions.DependencyInjection; +using TramsDataApi.DatabaseModels; + +namespace TramsDataApi.Setup; + +public static class HealthCheckSetup +{ + public static void AddHealthChecks(IServiceCollection services) { + services.AddHealthChecks(); + AddDbHealthChecks(services); + } + + public static void AddDbHealthChecks(IServiceCollection services) { + services.AddHealthChecks() + .AddDbContextCheck("Academies Database"); + } +} diff --git a/TramsDataApi/Startup.cs b/TramsDataApi/Startup.cs index 31a3ae13..43331330 100644 --- a/TramsDataApi/Startup.cs +++ b/TramsDataApi/Startup.cs @@ -7,6 +7,7 @@ namespace TramsDataApi { using DatabaseModels; using Dfe.Academies.Application.MappingProfiles; + using Dfe.Academies.Infrastructure; using Gateways; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; @@ -28,6 +29,7 @@ namespace TramsDataApi using TramsDataApi.ResponseModels; using TramsDataApi.SerilogCustomEnrichers; using TramsDataApi.Services; + using TramsDataApi.Setup; using TramsDataApi.Swagger; using UseCases; @@ -53,6 +55,9 @@ public void ConfigureServices(IServiceCollection services) services.AddDbContext(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); + // Register Health Checks + HealthCheckSetup.AddHealthChecks(services); + // Add connnection to MFSP services.AddHttpClient("MfspApiClient", (_, client) => { diff --git a/TramsDataApi/TramsDataApi.csproj b/TramsDataApi/TramsDataApi.csproj index 6210734e..6801dcbf 100644 --- a/TramsDataApi/TramsDataApi.csproj +++ b/TramsDataApi/TramsDataApi.csproj @@ -32,6 +32,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive +