using System.Net; using System.Reflection; using System.Text.RegularExpressions; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using PlotLine.Data; namespace PlotLine.Controllers; [AllowAnonymous] [ApiExplorerSettings(IgnoreApi=true)] public sealed class DeploymentHealthController(IDeploymentHealthRepository database) : Controller { [HttpGet("/_deployment/health")] [ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] public async Task Read(CancellationToken cancellationToken) { // Forwarded headers have already restored the external client's address. // This endpoint is for the local activation helper, never the public proxy. if(HttpContext.Connection.RemoteIpAddress is not { } ip || !IPAddress.IsLoopback(ip)) return NotFound(); try { var state=await database.ReadAsync(cancellationToken); if(!state.LedgerReady)return StatusCode(503,new {healthy=false}); var info=typeof(Program).Assembly.GetCustomAttribute()?.InformationalVersion??""; var sha=Regex.Match(info,@"\+([a-f0-9]{40})").Groups[1].Value; if(sha.Length!=40)return StatusCode(503,new {healthy=false}); return Json(new {healthy=true,version=info.Split('+')[0],sourceCommit=sha,database=state.DatabaseName}); } catch(Exception) when(!cancellationToken.IsCancellationRequested) { // Never return SQL diagnostics or connection information to HTTP clients. return StatusCode(503,new {healthy=false}); } } }