File: Utils\EnvironmentChecker\LegacyTelemetryHookCheck.cs
Web Access
Project: src\src\Aspire.Cli\Aspire.Cli.csproj (aspire)
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
 
using System.Globalization;
using System.Text.Json;
using Aspire.Cli.Agents;
using Aspire.Cli.Resources;
using Microsoft.Extensions.Logging;
 
namespace Aspire.Cli.Utils.EnvironmentChecker;
 
internal sealed class LegacyTelemetryHookCheck(
    IEnumerable<IAgentClient> clients,
    ILogger<LegacyTelemetryHookCheck> logger) : IEnvironmentCheck
{
    internal static string GetCheckName(string clientId) => $"agent-telemetry-hook-{clientId}";
 
    public int Order => 100;
 
    public async Task<IReadOnlyList<EnvironmentCheckResult>> CheckAsync(CancellationToken cancellationToken = default)
    {
        var results = new List<EnvironmentCheckResult>();
 
        foreach (var client in clients)
        {
            string? path;
            try
            {
                path = await client.FindLegacyTelemetryHookAsync(cancellationToken);
            }
            catch (Exception ex) when (ex is JsonException or IOException or UnauthorizedAccessException)
            {
                // A malformed file for one client must not hide a legacy hook for another client.
                logger.LogDebug(ex, "Could not inspect {Client} telemetry hook configuration.", client.DisplayName);
                continue;
            }
 
            if (path is not null)
            {
                // Init refuses to write through a symbolic link (ConfigurationHelper.ValidateSymbolicLinkPolicy),
                // so the init command alone cannot fix a hook found through one.
                var fix = new FileInfo(path).LinkTarget is not null
                    ? string.Format(CultureInfo.CurrentCulture, DoctorCommandStrings.LegacyTelemetryHookSymlinkFixFormat, path, client.Id)
                    : string.Format(CultureInfo.CurrentCulture, DoctorCommandStrings.LegacyTelemetryHookFixFormat, client.Id);
                results.Add(new EnvironmentCheckResult
                {
                    Category = EnvironmentCheckCategories.Environment,
                    Name = GetCheckName(client.Id),
                    Status = EnvironmentCheckStatus.Warning,
                    Message = string.Format(CultureInfo.CurrentCulture, DoctorCommandStrings.LegacyTelemetryHookMessageFormat, client.DisplayName),
                    Fix = fix,
                    Details = path,
                });
            }
        }
 
        return results;
    }
}