using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace StellaOps.Worker.Health;
///
/// Extension methods to add lightweight health endpoints to worker services.
///
public static class WorkerHealthExtensions
{
///
/// Registers a health check that tracks whether the host has fully started.
/// Call this on builder.Services before building the application.
///
public static IServiceCollection AddWorkerHealthChecks(this IServiceCollection services)
{
services.AddHealthChecks()
.AddCheck("host_started", tags: ["ready"]);
return services;
}
///
/// Maps /health/liveness (always 200) and /health/readiness
/// (checks registered health checks) endpoints.
///
public static WebApplication MapWorkerHealthEndpoints(this WebApplication app)
{
// Liveness: always returns 200 if the process is running
app.MapGet("/health/liveness", () => Results.Ok("Alive"))
.ExcludeFromDescription();
// Readiness: runs all registered health checks tagged "ready"
app.MapHealthChecks("/health/readiness", new HealthCheckOptions
{
Predicate = check => check.Tags.Contains("ready"),
ResultStatusCodes =
{
[HealthStatus.Healthy] = StatusCodes.Status200OK,
[HealthStatus.Degraded] = StatusCodes.Status503ServiceUnavailable,
[HealthStatus.Unhealthy] = StatusCodes.Status503ServiceUnavailable,
},
});
return app;
}
}