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; private readonly IConnectionMultiplexer? _redis; // 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) { _db = db; _redis = redis; } /// Liveness — the process is up. [HttpGet("/health")] public IActionResult Health() => Ok(new { status = "ok" }); /// Readiness — Postgres + Redis are reachable. [HttpGet("/health/ready")] public async Task Ready(CancellationToken ct) { var checks = new Dictionary(); try { await _db.Database.CanConnectAsync(ct); checks["postgres"] = "ok"; } catch (Exception ex) { checks["postgres"] = $"error: {ex.Message}"; } try { checks["redis"] = _redis == null ? "not_configured" : (_redis.IsConnected ? "ok" : "disconnected"); } catch (Exception ex) { checks["redis"] = $"error: {ex.Message}"; } var healthy = checks.Values.All(v => v is "ok" or "not_configured"); return healthy ? Ok(new { status = "ok", checks }) : StatusCode(503, new { status = "degraded", checks }); } }