using Khaemhat.Application.Instance;
using Khaemhat.Core.Common;
namespace Khaemhat.Web.Hosting;
///
/// Health endpoints for Docker and reverse proxies (SPEC ยง16.1, ADR 0012):
/// /health/live says the process answers (the image HEALTHCHECK), /health/ready says it can serve
/// requests (the start sequence completed: databases migrated), /health summarises both with the version.
/// They carry no personal or configuration data and need no authentication.
///
public static class HealthEndpoints
{
/// Maps the three health endpoints.
/// The application's route builder.
/// The route builder.
public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
endpoints.MapGet("/health/live", () => Results.Text("live", "text/plain"))
.ExcludeFromDescription();
endpoints.MapGet("/health/ready", (BootstrapState state) => state.IsReady
? Results.Text("ready", "text/plain")
: Results.Text(state.Phase == BootstrapPhase.Failed ? "failed" : "starting", "text/plain", statusCode: StatusCodes.Status503ServiceUnavailable))
.ExcludeFromDescription();
endpoints.MapGet("/health", (ProductVersion version, BootstrapState state) => Results.Json(
new HealthReport(
Status: state.IsReady ? "ok" : state.Phase == BootstrapPhase.Failed ? "failed" : "starting",
Live: true,
Ready: state.IsReady,
Version: version.Version,
Revision: version.Revision),
statusCode: state.IsReady ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable))
.ExcludeFromDescription();
return endpoints;
}
/// The body of /health.
/// ok when the instance is live and ready, starting or failed otherwise.
/// Whether the process answers.
/// Whether the instance can serve requests.
/// Product version (SemVer).
/// Source revision.
public sealed record HealthReport(string Status, bool Live, bool Ready, string Version, string Revision);
}