|
| 1 | +#nullable enable |
| 2 | +using System; |
| 3 | +using System.IO; |
| 4 | +using System.Net; |
| 5 | +using System.Text; |
| 6 | +using System.Threading; |
| 7 | +using System.Threading.Tasks; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | + |
| 10 | +namespace InstDotNet; |
| 11 | + |
| 12 | +/// <summary> |
| 13 | +/// HTTP server for health check endpoint |
| 14 | +/// </summary> |
| 15 | +public static class HealthCheckServer |
| 16 | +{ |
| 17 | + private static HttpListener? _listener; |
| 18 | + private static Task? _serverTask; |
| 19 | + private static CancellationTokenSource? _cts; |
| 20 | + private static ILogger? _logger; |
| 21 | + private static int _port = 8080; |
| 22 | + |
| 23 | + /// <summary> |
| 24 | + /// Start the health check HTTP server |
| 25 | + /// </summary> |
| 26 | + public static void Start(int port = 8080, ILogger? logger = null) |
| 27 | + { |
| 28 | + _port = port; |
| 29 | + _logger = logger; |
| 30 | + _cts = new CancellationTokenSource(); |
| 31 | + |
| 32 | + _listener = new HttpListener(); |
| 33 | + _listener.Prefixes.Add($"http://+:{port}/"); |
| 34 | + |
| 35 | + try |
| 36 | + { |
| 37 | + _listener.Start(); |
| 38 | + _logger?.LogInformation("Health check server started on port {Port}", port); |
| 39 | + |
| 40 | + _serverTask = Task.Run(async () => await ListenAsync(_cts.Token), _cts.Token); |
| 41 | + } |
| 42 | + catch (Exception ex) |
| 43 | + { |
| 44 | + _logger?.LogError(ex, "Failed to start health check server on port {Port}", port); |
| 45 | + throw; |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + /// <summary> |
| 50 | + /// Stop the health check server |
| 51 | + /// </summary> |
| 52 | + public static void Stop() |
| 53 | + { |
| 54 | + _cts?.Cancel(); |
| 55 | + _listener?.Stop(); |
| 56 | + _listener?.Close(); |
| 57 | + _logger?.LogInformation("Health check server stopped"); |
| 58 | + } |
| 59 | + |
| 60 | + private static async Task ListenAsync(CancellationToken cancellationToken) |
| 61 | + { |
| 62 | + while (!cancellationToken.IsCancellationRequested && _listener != null && _listener.IsListening) |
| 63 | + { |
| 64 | + try |
| 65 | + { |
| 66 | + var context = await _listener.GetContextAsync().ConfigureAwait(false); |
| 67 | + _ = Task.Run(() => HandleRequest(context), cancellationToken); |
| 68 | + } |
| 69 | + catch (ObjectDisposedException) |
| 70 | + { |
| 71 | + // Listener was closed, exit gracefully |
| 72 | + break; |
| 73 | + } |
| 74 | + catch (HttpListenerException ex) |
| 75 | + { |
| 76 | + _logger?.LogWarning(ex, "Health check server error"); |
| 77 | + if (!_listener.IsListening) |
| 78 | + break; |
| 79 | + } |
| 80 | + catch (Exception ex) |
| 81 | + { |
| 82 | + _logger?.LogError(ex, "Unexpected error in health check server"); |
| 83 | + } |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + private static void HandleRequest(HttpListenerContext context) |
| 88 | + { |
| 89 | + try |
| 90 | + { |
| 91 | + var request = context.Request; |
| 92 | + var response = context.Response; |
| 93 | + |
| 94 | + // Only handle GET requests to /health |
| 95 | + if (request.HttpMethod == "GET" && request.Url?.AbsolutePath == "/health") |
| 96 | + { |
| 97 | + var status = HealthCheck.GetStatus(); |
| 98 | + var json = HealthCheck.GetStatusJson(); |
| 99 | + |
| 100 | + // Set status code based on health |
| 101 | + response.StatusCode = status.Status == "healthy" ? 200 : 503; |
| 102 | + response.ContentType = "application/json"; |
| 103 | + response.ContentEncoding = Encoding.UTF8; |
| 104 | + |
| 105 | + var buffer = Encoding.UTF8.GetBytes(json); |
| 106 | + response.ContentLength64 = buffer.Length; |
| 107 | + response.OutputStream.Write(buffer, 0, buffer.Length); |
| 108 | + response.OutputStream.Close(); |
| 109 | + |
| 110 | + _logger?.LogDebug("Health check request: {Status}", status.Status); |
| 111 | + } |
| 112 | + else |
| 113 | + { |
| 114 | + // 404 for other paths |
| 115 | + response.StatusCode = 404; |
| 116 | + response.Close(); |
| 117 | + } |
| 118 | + } |
| 119 | + catch (Exception ex) |
| 120 | + { |
| 121 | + _logger?.LogError(ex, "Error handling health check request"); |
| 122 | + try |
| 123 | + { |
| 124 | + context.Response.StatusCode = 500; |
| 125 | + context.Response.Close(); |
| 126 | + } |
| 127 | + catch |
| 128 | + { |
| 129 | + // Ignore errors when closing response |
| 130 | + } |
| 131 | + } |
| 132 | + } |
| 133 | +} |
| 134 | + |
0 commit comments