File: Health\AspireHttpHealthCheck.cs
Web Access
Project: src\src\Aspire.Hosting\Aspire.Hosting.csproj (Aspire.Hosting)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using System.Buffers;
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using Microsoft.Extensions.Diagnostics.HealthChecks;
 
namespace Aspire.Hosting.Health;
 
/// <summary>
/// Polls an HTTP endpoint and parses the response. Supports the Aspire health check JSON format
/// (written by <c>Aspire.HealthChecks.AspireHealthCheckResponseWriter</c>), whose individual entries are
/// expanded into separate health reports by <see cref="ResourceHealthCheckService"/>.
/// </summary>
internal static class AspireHttpHealthCheck
{
    // Health responses are small. The limit keeps a misbehaving JSON endpoint from making the AppHost buffer an
    // unbounded body; larger responses are treated as not being in the Aspire format.
    internal const int MaxResponseBodyBytes = 1024 * 1024;
 
    /// <summary>
    /// Checks the health of <paramref name="uri"/>. The HTTP status code is always compared with <paramref name="expectedStatusCode"/>.
    /// If the response is in the Aspire JSON format, its entries are also returned in the result data for expansion.
    /// </summary>
    public static async Task<HealthCheckResult> CheckUriAsync(Uri uri, int expectedStatusCode, Func<HttpClient> httpClientFactory, HealthCheckContext context, CancellationToken cancellationToken)
    {
        try
        {
            using var timeoutSource = new CancellationTokenSource(HttpHealthCheckHelpers.DefaultHttpTimeout);
            using var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken);
            using var response = await httpClientFactory().GetAsync(uri, HttpCompletionOption.ResponseHeadersRead, linkedSource.Token).ConfigureAwait(false);
 
            var statusCodeMatches = (int)response.StatusCode == expectedStatusCode;
            var statusCodeDescription = statusCodeMatches
                ? null
                : $"Request to {HttpHealthCheckHelpers.SanitizeUri(uri)} returned {(int)response.StatusCode} {response.StatusCode}";
 
            // Only read the body when it is JSON so that probes against arbitrary endpoints (for example, "/" serving HTML)
            // keep the headers-only behavior. The body is parsed regardless of the status code because services
            // commonly return 503 for unhealthy dependencies while still describing each individual check.
            if (IsJsonContent(response))
            {
                var body = await TryReadBoundedBodyAsync(response.Content, linkedSource.Token, cancellationToken).ConfigureAwait(false);
                if (body is not null && TryParseHealthCheckResponse(body, out var entries, out var reportedStatus))
                {
                    var data = new Dictionary<string, object>
                    {
                        [HealthCheckConstants.DataKeys.Entries] = entries
                    };
 
                    // The expected status code is part of the health check contract, so a mismatch fails the check even
                    // when the body reports healthy. Entries are still returned so each individual check is visible.
                    var status = statusCodeMatches
                        ? GetOverallStatus(reportedStatus, entries)
                        : context.Registration.FailureStatus;
 
                    return new HealthCheckResult(status, statusCodeDescription, data: data);
                }
            }
 
            return statusCodeMatches
                ? HealthCheckResult.Healthy()
                : new HealthCheckResult(context.Registration.FailureStatus, statusCodeDescription);
        }
        catch (Exception ex)
        {
            var friendlyMessage = HttpHealthCheckHelpers.GetFriendlyErrorMessage(uri, ex, cancellationToken);
            return new HealthCheckResult(context.Registration.FailureStatus, friendlyMessage, ex);
        }
    }
 
    private static HealthStatus GetOverallStatus(HealthStatus? reportedStatus, IReadOnlyDictionary<string, AspireHealthCheckEntry> entries)
    {
        // HealthStatus is ordered Unhealthy < Degraded < Healthy. Use the worst of the reported overall status and the
        // individual entries so a missing or inconsistent overall status cannot hide a failing entry.
        var status = reportedStatus ?? HealthStatus.Healthy;
        foreach (var entry in entries.Values)
        {
            if (entry.Status < status)
            {
                status = entry.Status;
            }
        }
 
        return status;
    }
 
    private static bool IsJsonContent(HttpResponseMessage response)
    {
        var mediaType = response.Content.Headers.ContentType?.MediaType;
        return mediaType is not null &&
            (mediaType.Equals("application/json", StringComparison.OrdinalIgnoreCase) ||
             mediaType.EndsWith("+json", StringComparison.OrdinalIgnoreCase));
    }
 
    private static async Task<byte[]?> TryReadBoundedBodyAsync(HttpContent content, CancellationToken readToken, CancellationToken callerToken)
    {
        if (content.Headers.ContentLength > MaxResponseBodyBytes)
        {
            return null;
        }
 
        var buffer = ArrayPool<byte>.Shared.Rent(16 * 1024);
        try
        {
            using var stream = await content.ReadAsStreamAsync(readToken).ConfigureAwait(false);
            using var body = new MemoryStream();
            int read;
            while ((read = await stream.ReadAsync(buffer.AsMemory(), readToken).ConfigureAwait(false)) > 0)
            {
                if (body.Length + read > MaxResponseBodyBytes)
                {
                    return null;
                }
 
                body.Write(buffer, 0, read);
            }
 
            return body.ToArray();
        }
        catch (Exception ex) when (ex is IOException or HttpRequestException ||
            (ex is OperationCanceledException && !callerToken.IsCancellationRequested))
        {
            // The response headers already arrived, so a body that stalls or fails to stream is treated as not being
            // in the Aspire format and the check falls back to the status code, matching the headers-only behavior.
            return null;
        }
        finally
        {
            ArrayPool<byte>.Shared.Return(buffer);
        }
    }
 
    // Parses the format written by Aspire.HealthChecks.AspireHealthCheckResponseWriter, for example:
    //   {
    //     "status": "Unhealthy",
    //     "totalDuration": "00:00:00.0123",
    //     "entries": {
    //       "database": { "status": "Healthy", "duration": "00:00:00.001", "description": "Database is responsive" },
    //       "external_api": { "status": "Unhealthy", "description": "...", "exception": "Connection timeout" }
    //     }
    //   }
    // The response comes from another process, so each value is type-checked. A malformed value only affects its own
    // entry (an unrecognized entry status becomes Unhealthy) instead of discarding the valid sibling entries.
    internal static bool TryParseHealthCheckResponse(
        ReadOnlyMemory<byte> json,
        [NotNullWhen(true)] out Dictionary<string, AspireHealthCheckEntry>? entries,
        out HealthStatus? reportedStatus)
    {
        entries = null;
        reportedStatus = null;
 
        JsonDocument document;
        try
        {
            document = JsonDocument.Parse(json);
        }
        catch (JsonException)
        {
            return false;
        }
 
        using (document)
        {
            var root = document.RootElement;
            if (root.ValueKind != JsonValueKind.Object ||
                !root.TryGetProperty(HealthCheckConstants.JsonProperties.Entries, out var entriesElement) ||
                entriesElement.ValueKind != JsonValueKind.Object)
            {
                return false;
            }
 
            if (root.TryGetProperty(HealthCheckConstants.JsonProperties.Status, out var statusElement))
            {
                reportedStatus = TryParseStatus(statusElement, out var status) ? status : HealthStatus.Unhealthy;
            }
 
            entries = [];
            foreach (var entryProperty in entriesElement.EnumerateObject())
            {
                var entryValue = entryProperty.Value;
                var status = HealthStatus.Unhealthy;
                string? description = null;
                string? exceptionText = null;
 
                if (entryValue.ValueKind == JsonValueKind.Object)
                {
                    if (entryValue.TryGetProperty(HealthCheckConstants.JsonProperties.Status, out var entryStatusElement) &&
                        TryParseStatus(entryStatusElement, out var parsedStatus))
                    {
                        status = parsedStatus;
                    }
 
                    description = GetStringOrNull(entryValue, HealthCheckConstants.JsonProperties.Description);
                    exceptionText = GetStringOrNull(entryValue, HealthCheckConstants.JsonProperties.Exception);
                }
 
                entries[entryProperty.Name] = new AspireHealthCheckEntry(status, description, string.IsNullOrEmpty(exceptionText) ? null : exceptionText);
            }
 
            return true;
        }
    }
 
    private static bool TryParseStatus(JsonElement element, out HealthStatus status)
    {
        status = default;
 
        // Only named values are accepted. Enum.TryParse would also accept numeric strings such as "7".
        return element.ValueKind == JsonValueKind.String &&
            Enum.TryParse(element.GetString(), ignoreCase: true, out status) &&
            Enum.IsDefined(status) &&
            !int.TryParse(element.GetString(), out _);
    }
 
    private static string? GetStringOrNull(JsonElement element, string propertyName)
    {
        return element.TryGetProperty(propertyName, out var value) && value.ValueKind == JsonValueKind.String
            ? value.GetString()
            : null;
    }
}