2026-09-01 16:37:53 +00:00
|
|
|
using Microsoft.AspNetCore.Mvc;
|
|
|
|
|
using Microsoft.EntityFrameworkCore;
|
|
|
|
|
using StackExchange.Redis;
|
|
|
|
|
using w4c_workflows.Data;
|
|
|
|
|
|
|
|
|
|
namespace w4c_workflows.Controllers;
|
|
|
|
|
|
|
|
|
|
[ApiController]
|
|
|
|
|
public class HealthController : ControllerBase
|
|
|
|
|
{
|
|
|
|
|
private readonly WorkflowsDbContext _db;
|
2026-09-12 20:29:19 +00:00
|
|
|
private readonly IConnectionMultiplexer? _redis;
|
2026-09-01 16:37:53 +00:00
|
|
|
|
2026-09-12 20:29:19 +00:00
|
|
|
// Redis is absent in Lite mode (in-memory transport). The dependency is
|
|
|
|
|
// optional so liveness/readiness still resolve instead of failing DI.
|
|
|
|
|
public HealthController(WorkflowsDbContext db, IConnectionMultiplexer? redis = null)
|
2026-09-01 16:37:53 +00:00
|
|
|
{
|
|
|
|
|
_db = db;
|
|
|
|
|
_redis = redis;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>Liveness — the process is up.</summary>
|
|
|
|
|
[HttpGet("/health")]
|
|
|
|
|
public IActionResult Health() => Ok(new { status = "ok" });
|
|
|
|
|
|
|
|
|
|
/// <summary>Readiness — Postgres + Redis are reachable.</summary>
|
|
|
|
|
[HttpGet("/health/ready")]
|
|
|
|
|
public async Task<IActionResult> Ready(CancellationToken ct)
|
|
|
|
|
{
|
|
|
|
|
var checks = new Dictionary<string, string>();
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await _db.Database.CanConnectAsync(ct);
|
|
|
|
|
checks["postgres"] = "ok";
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
checks["postgres"] = $"error: {ex.Message}";
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
2026-09-12 20:29:19 +00:00
|
|
|
checks["redis"] = _redis == null
|
|
|
|
|
? "not_configured"
|
|
|
|
|
: (_redis.IsConnected ? "ok" : "disconnected");
|
2026-09-01 16:37:53 +00:00
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
|
|
|
|
checks["redis"] = $"error: {ex.Message}";
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-12 20:29:19 +00:00
|
|
|
var healthy = checks.Values.All(v => v is "ok" or "not_configured");
|
2026-09-01 16:37:53 +00:00
|
|
|
return healthy ? Ok(new { status = "ok", checks }) : StatusCode(503, new { status = "degraded", checks });
|
|
|
|
|
}
|
|
|
|
|
}
|