File: Commands\StopCommand.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.CommandLine;
using System.Globalization;
using Aspire.Cli.Backchannel;
using Aspire.Cli.Interaction;
using Aspire.Cli.Processes;
using Aspire.Cli.Projects;
using Aspire.Cli.Resources;
using Aspire.Cli.Telemetry;
using Aspire.Cli.Utils;
using Aspire.Hosting.Utils;
using Microsoft.Extensions.Logging;
using Semver;
using StreamJsonRpc;
 
namespace Aspire.Cli.Commands;
 
internal sealed partial class StopCommand : BaseCommand
{
    internal override HelpGroup HelpGroup => HelpGroup.AppCommands;
 
    protected override bool UpdateNotificationsEnabled => true;
 
    private readonly AppHostConnectionResolver _connectionResolver;
    private readonly ILogger<StopCommand> _logger;
    private readonly ICliHostEnvironment _hostEnvironment;
    private readonly IEnvironment _environment;
    private readonly ProcessTreeGracefulShutdownService _processShutdownService;
    private readonly OrphanedAppHostCollector _collector;
    private readonly ProfilingTelemetry _profilingTelemetry;
    private readonly IProjectLocator _projectLocator;
    private readonly IAppHostInfoResolver _appHostInfoResolver;
    private readonly ILanguageDiscovery _languageDiscovery;
    private readonly DcpWorkloadCleanupService _dcpCleanupService;
    private readonly TimeProvider _timeProvider;
    private readonly Lock _resourceTeardownExitCodeLock = new();
 
    // Per-invocation state. A command instance handles a single invocation.
    private bool _waitForResourceTeardown;
    private TimeSpan _resourceTeardownTimeout;
    private int _appHostsStoppedWithoutTeardownWait;
    private int _resourceTeardownExitCode;
 
    // Stopping a container sends SIGTERM and waits up to 10 seconds before SIGKILL, and DCP tears resources down in
    // parallel, so a healthy teardown takes seconds. The extra headroom covers slow container runtimes.
    internal const int DefaultResourceTeardownTimeoutSeconds = 120;
 
    // CancellationTokenSource's underlying timer accepts at most uint.MaxValue - 1 milliseconds.
    internal const int MaximumResourceTeardownTimeoutSeconds = (int)((uint.MaxValue - 1) / 1000);
 
    private const int MinimumHostingMajorVersionForPersistentResourceCleanup = 13;
    private const int MinimumHostingMinorVersionForPersistentResourceCleanup = 5;
    private const string MinimumHostingVersionForPersistentResourceCleanupDisplay = "13.5.0";
    private const int MinimumHostingMajorVersionForPersistentVolumeCleanup = 13;
    private const int MinimumHostingMinorVersionForPersistentVolumeCleanup = 6;
    private const string MinimumHostingVersionForPersistentVolumeCleanupDisplay = "13.6.0";
 
    private static readonly OptionWithLegacy<FileInfo?> s_appHostOption = new("--apphost", "--project", StopCommandStrings.ProjectArgumentDescription);
 
    private static readonly Option<bool> s_allOption = new("--all")
    {
        Description = StopCommandStrings.AllOptionDescription
    };
 
    private static readonly Option<bool> s_forceOption = new("--force")
    {
        Description = StopCommandStrings.ForceOptionDescription
    };
 
    private static readonly Option<int?> s_pidOption = new("--pid")
    {
        Description = StopCommandStrings.PidOptionDescription
    };
 
    private static readonly Option<bool> s_volumesOption = new("--volumes")
    {
        Description = StopCommandStrings.VolumesOptionDescription
    };
 
    private static readonly Option<bool> s_waitOption = new("--wait")
    {
        Description = StopCommandStrings.WaitOptionDescription
    };
 
    private static readonly Option<int> s_timeoutOption = new("--timeout")
    {
        Description = StopCommandStrings.TimeoutOptionDescription,
        DefaultValueFactory = _ => DefaultResourceTeardownTimeoutSeconds
    };
 
    public StopCommand(
        AppHostConnectionResolver connectionResolver,
        ICliHostEnvironment hostEnvironment,
        IEnvironment environment,
        ProcessTreeGracefulShutdownService processShutdownService,
        IAuxiliaryBackchannelMonitor backchannelMonitor,
        IProcessIdentityProvider processIdentityProvider,
        TrayProtocolOutput protocolOutput,
        IProjectLocator projectLocator,
        IAppHostInfoResolver appHostInfoResolver,
        ILanguageDiscovery languageDiscovery,
        DcpWorkloadCleanupService dcpCleanupService,
        OrphanedAppHostCollector collector,
        ILogger<StopCommand> logger,
        ProfilingTelemetry profilingTelemetry,
        TimeProvider timeProvider,
        CommonCommandServices services)
        : base("stop", StopCommandStrings.Description, services)
    {
        _connectionResolver = connectionResolver;
        _hostEnvironment = hostEnvironment;
        _environment = environment;
        _processShutdownService = processShutdownService;
        _backchannelMonitor = backchannelMonitor;
        _processIdentityProvider = processIdentityProvider;
        _protocolOutput = protocolOutput;
        _projectLocator = projectLocator;
        _appHostInfoResolver = appHostInfoResolver;
        _languageDiscovery = languageDiscovery;
        _dcpCleanupService = dcpCleanupService;
        _collector = collector;
        _logger = logger;
        _profilingTelemetry = profilingTelemetry;
        _timeProvider = timeProvider;
 
        Options.Add(s_appHostOption);
        Options.Add(s_allOption);
        Options.Add(s_forceOption);
        Options.Add(s_pidOption);
        Options.Add(s_protocolVersionOption);
        Options.Add(s_startedAtOption);
        Options.Add(s_formatOption);
        Options.Add(s_volumesOption);
        Options.Add(s_waitOption);
        Options.Add(s_timeoutOption);
    }
 
    protected override async Task<CommandResult> ExecuteAsync(ParseResult parseResult, CancellationToken cancellationToken)
    {
        if (parseResult.GetValue(s_protocolVersionOption) is not null)
        {
            return await ExecuteProtocolAsync(parseResult, cancellationToken).ConfigureAwait(false);
        }
 
        // A supplied lifetime must never be silently downgraded to legacy PID-only stopping.
        if (parseResult.GetResult(s_startedAtOption) is { Implicit: false } ||
            parseResult.GetResult(s_formatOption) is { Implicit: false })
        {
            return CommandResult.Failure(CliExitCodes.InvalidCommand, StopCommandStrings.ProtocolRequiresExactIdentity);
        }
 
        var passedAppHostProjectFile = parseResult.GetValue(s_appHostOption);
        var stopAll = parseResult.GetValue(s_allOption);
        var force = parseResult.GetValue(s_forceOption);
        var processId = parseResult.GetValue(s_pidOption);
        var volumes = parseResult.GetValue(s_volumesOption);
        _waitForResourceTeardown = parseResult.GetValue(s_waitOption);
        var timeoutSeconds = parseResult.GetValue(s_timeoutOption);
        var timeoutSpecified = parseResult.GetResult(s_timeoutOption) is { Implicit: false };
        _appHostsStoppedWithoutTeardownWait = 0;
        _resourceTeardownExitCode = CliExitCodes.Success;
        using var activity = _profilingTelemetry.StartStopCommand(stopAll, passedAppHostProjectFile is not null);
 
        CommandResult result;
        if (timeoutSpecified && !_waitForResourceTeardown)
        {
            result = CommandResult.Failure(CliExitCodes.InvalidCommand, string.Format(CultureInfo.CurrentCulture, StopCommandStrings.TimeoutRequiresWait, s_timeoutOption.Name, s_waitOption.Name));
        }
        else if (timeoutSeconds is <= 0 or > MaximumResourceTeardownTimeoutSeconds)
        {
            result = CommandResult.Failure(CliExitCodes.InvalidCommand, string.Format(CultureInfo.CurrentCulture, StopCommandStrings.TimeoutInvalid, MaximumResourceTeardownTimeoutSeconds));
        }
        else
        {
            _resourceTeardownTimeout = TimeSpan.FromSeconds(timeoutSeconds);
            result = await ExecuteStopAsync(passedAppHostProjectFile, stopAll, force, processId, volumes, cancellationToken).ConfigureAwait(false);
        }
 
        // An unconfirmed resource teardown does not fail the stop itself, so the remaining steps (such as the
        // persistent resource cleanup of --force) still run, but the command must not report success.
        if (result.ExitCode == CliExitCodes.Success && _resourceTeardownExitCode != CliExitCodes.Success)
        {
            result = CommandResult.FromExitCode(_resourceTeardownExitCode);
        }
 
        CompleteStopActivity(activity, result.ExitCode);
 
        if (_appHostsStoppedWithoutTeardownWait > 0)
        {
            // The AppHost process exits before DCP has finished tearing its resources down, so a start issued right
            // away can still find containers with fixed names running and adopt them just before they are removed.
            InteractionService.DisplayMessage(KnownEmojis.Information, string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourceTeardownMayContinue, s_waitOption.Name));
        }
 
        return result;
    }
 
    private async Task<CommandResult> ExecuteStopAsync(FileInfo? passedAppHostProjectFile, bool stopAll, bool force, int? processId, bool volumes, CancellationToken cancellationToken)
    {
        if (processId is { } pid)
        {
            if (pid <= 0)
            {
                return CommandResult.Failure(CliExitCodes.InvalidCommand, StopCommandStrings.PidMustBePositive);
            }
 
            if (stopAll || force || volumes)
            {
                return CommandResult.Failure(CliExitCodes.InvalidCommand, string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AllAndProjectMutuallyExclusive, s_pidOption.Name, stopAll ? s_allOption.Name : force ? s_forceOption.Name : s_volumesOption.Name));
            }
 
            // An instance selector must never fall through to project discovery, project-wide
            // batching, or orphan/persistent cleanup, even when the selected instance disappears.
            return CommandResult.FromExitCode(await StopAppHostByPidAsync(pid, passedAppHostProjectFile, cancellationToken).ConfigureAwait(false));
        }
 
        // Validate mutual exclusivity of --all and --project
        if (stopAll && passedAppHostProjectFile is not null)
        {
            return CommandResult.Failure(CliExitCodes.FailedToFindProject, string.Format(CultureInfo.InvariantCulture, StopCommandStrings.AllAndProjectMutuallyExclusive, s_allOption.Name, s_appHostOption.Name));
        }
 
        if (stopAll && force)
        {
            return CommandResult.Failure(CliExitCodes.InvalidCommand, string.Format(CultureInfo.InvariantCulture, StopCommandStrings.AllAndProjectMutuallyExclusive, s_allOption.Name, s_forceOption.Name));
        }
 
        if (volumes && !force)
        {
            return CommandResult.Failure(CliExitCodes.InvalidCommand, string.Format(CultureInfo.InvariantCulture, StopCommandStrings.VolumesRequiresForce, s_volumesOption.Name, s_forceOption.Name));
        }
 
        if (force)
        {
            return CommandResult.FromExitCode(await ForceStopAppHostAsync(passedAppHostProjectFile, volumes, cancellationToken).ConfigureAwait(false));
        }
 
        // Handle --all: stop all running AppHosts
        if (stopAll)
        {
            return CommandResult.FromExitCode(await StopAllAppHostsAsync(cancellationToken));
        }
 
        // In non-interactive mode, try to auto-resolve without prompting
        if (!_hostEnvironment.SupportsInteractiveInput)
        {
            return CommandResult.FromExitCode(await ExecuteNonInteractiveAsync(passedAppHostProjectFile, cancellationToken));
        }
 
        return CommandResult.FromExitCode(await ExecuteInteractiveAsync(passedAppHostProjectFile, cancellationToken));
    }
 
    private async Task<int> StopAppHostByPidAsync(int processId, FileInfo? appHostFile, CancellationToken cancellationToken)
    {
        var results = await _connectionResolver.ResolveAllConnectionsAsync(
            SharedCommandStrings.ScanningForRunningAppHosts,
            cancellationToken,
            pruneOrphanedSockets: false).ConfigureAwait(false);
 
        var connections = results
            .Where(result => result.Connection?.AppHostInfo is { } info &&
                info.ProcessId == processId &&
                (appHostFile is null || GetAppHostPathComparer().Equals(info.AppHostPath, appHostFile.FullName)))
            .Select(result => result.Connection!)
            .ToArray();
 
        if (connections.Length == 0)
        {
            InteractionService.DisplayError(appHostFile is null
                ? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostNotRunningWithPid, processId)
                : string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostNotRunningAtPathWithPid, appHostFile.FullName, processId));
            return CliExitCodes.FailedToFindProject;
        }
 
        if (connections.Length != 1)
        {
            InteractionService.DisplayError(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AmbiguousAppHostPid, processId));
            return CliExitCodes.FailedToFindProject;
        }
 
        var connection = connections[0];
        _profilingTelemetry.CurrentActivity.SetAppHostStopCount(1);
        var identifier = GetAppHostIdentifier(connection, GetSingleAppHostDisplayPath(connection), includeProcessId: true);
        return await StopAppHostAsync(connection, identifier, useConnectionOnly: true, cancellationToken).ConfigureAwait(false);
    }
 
    private async Task<int> ForceStopAppHostAsync(FileInfo? passedAppHostProjectFile, bool deleteVolumes, CancellationToken cancellationToken)
    {
        var stopResult = _hostEnvironment.SupportsInteractiveInput
            ? await ExecuteInteractiveWithResultAsync(passedAppHostProjectFile, cancellationToken).ConfigureAwait(false)
            : await ExecuteNonInteractiveWithResultAsync(passedAppHostProjectFile, cancellationToken, treatNotRunningAsSuccess: true).ConfigureAwait(false);
 
        if (stopResult.ExitCode != CliExitCodes.Success)
        {
            return stopResult.ExitCode;
        }
 
        var appHostFile = stopResult.AppHostFile;
        if (appHostFile is null && passedAppHostProjectFile is not null && passedAppHostProjectFile.Exists)
        {
            appHostFile = passedAppHostProjectFile;
        }
 
        appHostFile ??= await TryResolveAppHostFileAsync(passedAppHostProjectFile, cancellationToken).ConfigureAwait(false);
        if (appHostFile is null)
        {
            InteractionService.DisplayError(StopCommandStrings.CouldNotDetermineAppHostPath);
            return CliExitCodes.FailedToFindProject;
        }
 
        return await CleanupPersistentResourcesAsync(appHostFile, deleteVolumes, cancellationToken).ConfigureAwait(false);
    }
 
    private async Task<FileInfo?> TryResolveAppHostFileAsync(
        FileInfo? passedAppHostProjectFile,
        CancellationToken cancellationToken,
        MultipleAppHostProjectsFoundBehavior? multipleAppHostBehaviorOverride = null)
    {
        var multipleAppHostBehavior = multipleAppHostBehaviorOverride ?? (_hostEnvironment.SupportsInteractiveInput
            ? MultipleAppHostProjectsFoundBehavior.Prompt
            : MultipleAppHostProjectsFoundBehavior.Throw);
 
        try
        {
            var searchResult = await _projectLocator.UseOrFindAppHostProjectFileAsync(
                passedAppHostProjectFile,
                multipleAppHostBehavior,
                createSettingsFile: false,
                cancellationToken).ConfigureAwait(false);
 
            return searchResult.SelectedProjectFile;
        }
        catch (ProjectLocatorException ex)
        {
            if (passedAppHostProjectFile is not null)
            {
                var projectOptionSpecifiedAsDirectory = Directory.Exists(passedAppHostProjectFile.FullName);
                var (_, errorMessage) = ProjectLocatorErrorHelper.GetExitCodeAndMessage(ex, projectOptionSpecifiedAsDirectory);
                InteractionService.DisplayError(errorMessage);
            }
            else
            {
                _logger.LogDebug(ex, "Failed to resolve AppHost project file for resource cleanup.");
            }
 
            return null;
        }
    }
 
    /// <summary>
    /// Handles the stop command in non-interactive mode by auto-resolving a single AppHost
    /// or returning an error when multiple AppHosts are running.
    /// </summary>
    private async Task<int> ExecuteNonInteractiveAsync(FileInfo? passedAppHostProjectFile, CancellationToken cancellationToken)
    {
        var result = await ExecuteNonInteractiveWithResultAsync(passedAppHostProjectFile, cancellationToken).ConfigureAwait(false);
        return result.ExitCode;
    }
 
    private async Task<StopAppHostResult> ExecuteNonInteractiveWithResultAsync(FileInfo? passedAppHostProjectFile, CancellationToken cancellationToken, bool treatNotRunningAsSuccess = false)
    {
        // If --project is specified, use the standard resolver (no prompting needed)
        if (passedAppHostProjectFile is not null)
        {
            return await ExecuteInteractiveWithResultAsync(passedAppHostProjectFile, cancellationToken).ConfigureAwait(false);
        }
 
        // Scan for all running AppHosts
        var allConnections = await _connectionResolver.ResolveAllConnectionsAsync(
            SharedCommandStrings.ScanningForRunningAppHosts,
            cancellationToken);
 
        if (allConnections.Length == 0)
        {
            if (treatNotRunningAsSuccess)
            {
                InteractionService.DisplayMessage(KnownEmojis.Information, SharedCommandStrings.AppHostNotRunning);
                return new StopAppHostResult(CliExitCodes.Success, null);
            }
 
            InteractionService.DisplayError(SharedCommandStrings.AppHostNotRunning);
            return new StopAppHostResult(CliExitCodes.FailedToFindProject, null);
        }
 
        // In non-interactive mode, only consider in-scope AppHosts (under current directory)
        // to avoid accidentally stopping unrelated AppHosts
        var inScopeConnections = allConnections.Where(c => c.Connection!.IsInScope).ToArray();
        if (inScopeConnections.Length == 0 && treatNotRunningAsSuccess)
        {
            InteractionService.DisplayMessage(KnownEmojis.Information, SharedCommandStrings.AppHostNotRunning);
            return new StopAppHostResult(CliExitCodes.Success, null);
        }
 
        // Single in-scope AppHost: auto-select it
        if (inScopeConnections.Length == 1)
        {
            var connection = inScopeConnections[0].Connection!;
            var appHostFile = GetAppHostFile(connection);
            if (appHostFile is not null)
            {
                // Reuse the connections already scanned above rather than scanning every socket a second
                // time. A rescan pays each unreachable socket's connect retry budget again.
                return await StopRunningAppHostsForResolvedFileAsync(appHostFile, allConnections, cancellationToken).ConfigureAwait(false);
            }
 
            _profilingTelemetry.CurrentActivity.SetAppHostStopCount(1);
            var exitCode = await StopAppHostAsync(connection, GetSingleAppHostDisplayPath(connection), useConnectionOnly: false, cancellationToken).ConfigureAwait(false);
            return new StopAppHostResult(exitCode, appHostFile);
        }
 
        // Multiple in-scope AppHosts or none in scope: error with guidance
        InteractionService.DisplayError(string.Format(CultureInfo.InvariantCulture, StopCommandStrings.MultipleAppHostsNonInteractive, s_appHostOption.Name, s_allOption.Name));
        return new StopAppHostResult(CliExitCodes.FailedToFindProject, null);
    }
 
    /// <summary>
    /// Handles the stop command in interactive mode, prompting the user to select an AppHost if multiple are running.
    /// </summary>
    private async Task<int> ExecuteInteractiveAsync(FileInfo? passedAppHostProjectFile, CancellationToken cancellationToken)
    {
        var result = await ExecuteInteractiveWithResultAsync(passedAppHostProjectFile, cancellationToken).ConfigureAwait(false);
        return result.ExitCode;
    }
 
    private async Task<StopAppHostResult> ExecuteInteractiveWithResultAsync(FileInfo? passedAppHostProjectFile, CancellationToken cancellationToken)
    {
        var result = await _connectionResolver.ResolveConnectionAsync(
            passedAppHostProjectFile,
            SharedCommandStrings.ScanningForRunningAppHosts,
            string.Format(CultureInfo.CurrentCulture, SharedCommandStrings.SelectAppHost, StopCommandStrings.SelectAppHostAction),
            SharedCommandStrings.AppHostNotRunning,
            cancellationToken,
            restrictToCurrentWorktree: true);
 
        if (!result.Success)
        {
            return new StopAppHostResult(AppHostConnectionResultHandler.DisplayFailureAsInformation(result, InteractionService), null);
        }
 
        var appHostFile = GetAppHostFile(result.Connection!);
        if (appHostFile is not null)
        {
            // The resolver returns a single connection, but every instance running at that path should be
            // stopped, so the full set is needed here.
            var allConnections = await _connectionResolver.ResolveAllConnectionsAsync(
                SharedCommandStrings.ScanningForRunningAppHosts,
                cancellationToken).ConfigureAwait(false);
 
            return await StopRunningAppHostsForResolvedFileAsync(appHostFile, allConnections, cancellationToken).ConfigureAwait(false);
        }
 
        _profilingTelemetry.CurrentActivity.SetAppHostStopCount(1);
        var exitCode = await StopAppHostAsync(result.Connection!, GetSingleAppHostDisplayPath(result.Connection!), useConnectionOnly: false, cancellationToken).ConfigureAwait(false);
        return new StopAppHostResult(exitCode, appHostFile);
    }
 
    private async Task<StopAppHostResult> StopRunningAppHostsForResolvedFileAsync(FileInfo appHostFile, AppHostConnectionResult[] allConnections, CancellationToken cancellationToken)
    {
        var canonicalAppHostPath = PathNormalizer.ResolveToFilesystemPath(appHostFile.FullName);
 
        var matchingConnections = allConnections
            .Where(result =>
                result is { Success: true, Connection.AppHostInfo.AppHostPath: { } connectionAppHostPath } &&
                StringComparers.FileSystemPath.Equals(
                    PathNormalizer.ResolveToFilesystemPath(connectionAppHostPath),
                    canonicalAppHostPath))
            .Select(result => result.Connection!)
            .ToArray();
 
        if (matchingConnections.Length == 0)
        {
            // Reachable when the AppHost exits between being resolved and these connections being
            // enumerated. Reporting it as not running is the right outcome for that race.
            var displayPath = Path.GetRelativePath(ExecutionContext.WorkingDirectory.FullName, appHostFile.FullName);
            InteractionService.DisplayMessage(KnownEmojis.Information, string.Format(CultureInfo.CurrentCulture, SharedCommandStrings.AppHostNotRunningAtPath, displayPath));
 
            return new StopAppHostResult(CliExitCodes.Success, null);
        }
 
        _profilingTelemetry.CurrentActivity.SetAppHostStopCount(matchingConnections.Length);
        var appHostPaths = matchingConnections.Select(GetAppHostPath).ToArray();
        var displayPaths = FileSystemHelper.ShortenPaths(appHostPaths, _environment);
        var includeProcessId = matchingConnections.Length > 1;
        var stopTasks = matchingConnections.Select(connection =>
        {
            var appHostPath = GetAppHostPath(connection);
            var displayPath = includeProcessId
                ? displayPaths[appHostPath]
                : GetSingleAppHostDisplayPath(connection);
            var appHostIdentifier = GetAppHostIdentifier(connection, displayPath, includeProcessId);
            return StopAppHostAsync(connection, appHostIdentifier, useConnectionOnly: false, cancellationToken);
        }).ToArray();
 
        var results = await Task.WhenAll(stopTasks).ConfigureAwait(false);
        var allStopped = results.All(exitCode => exitCode == CliExitCodes.Success);
 
        return new StopAppHostResult(allStopped ? CliExitCodes.Success : CliExitCodes.FailedToDotnetRunAppHost, appHostFile);
    }
 
    private async Task<int> CleanupPersistentResourcesAsync(FileInfo appHostFile, bool deleteVolumes, CancellationToken cancellationToken)
    {
        await WarnIfCleanupMayBeUnsupportedAsync(appHostFile, deleteVolumes, cancellationToken).ConfigureAwait(false);
 
        var appHostPath = appHostFile.FullName;
        var appHostDisplayPath = FileSystemHelper.ShortenPaths([appHostPath], _environment)[appHostPath];
        var workloadId = AppHostWorkloadId.Create(appHostFile);
        var cleanupResult = await InteractionService.ShowStatusAsync(
            string.Format(CultureInfo.CurrentCulture, StopCommandStrings.CleaningPersistentResources, appHostDisplayPath),
            () => _dcpCleanupService.CleanupAsync(workloadId, deleteVolumes, cancellationToken),
            emoji: KnownEmojis.Gear).ConfigureAwait(false);
 
        InteractionService.DisplayPlainText("");
 
        if (!cleanupResult.DcpFound)
        {
            InteractionService.DisplayError(StopCommandStrings.DcpCleanupUnavailable);
            return CliExitCodes.FailedToDotnetRunAppHost;
        }
 
        if (cleanupResult.ExitCode != 0)
        {
            var details = GetDcpCleanupErrorDetails(cleanupResult);
            InteractionService.DisplayError(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.DcpCleanupFailed, appHostDisplayPath, details));
            return CliExitCodes.FailedToDotnetRunAppHost;
        }
 
        InteractionService.DisplaySuccess(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.PersistentResourcesCleaned, appHostDisplayPath));
        return CliExitCodes.Success;
    }
 
    private async Task WarnIfCleanupMayBeUnsupportedAsync(FileInfo appHostFile, bool deleteVolumes, CancellationToken cancellationToken)
    {
        if (!IsDotNetAppHost(appHostFile))
        {
            return;
        }
 
        AppHostProjectInfo appHostInfo;
        try
        {
            appHostInfo = await _appHostInfoResolver.GetAppHostInfoAsync(appHostFile, cancellationToken).ConfigureAwait(false);
        }
        catch (Exception ex) when (ex is not OperationCanceledException)
        {
            _logger.LogDebug(ex, "Failed to inspect AppHost project for persistent resource cleanup compatibility.");
            InteractionService.DisplayMessage(KnownEmojis.PoliceCarLight, StopCommandStrings.DcpCleanupCompatibilityCheckFailed);
            return;
        }
 
        if (appHostInfo.ExitCode != 0 || !appHostInfo.IsAspireHost)
        {
            InteractionService.DisplayMessage(KnownEmojis.PoliceCarLight, StopCommandStrings.DcpCleanupCompatibilityCheckFailed);
            return;
        }
 
        var minimumMajorVersion = deleteVolumes
            ? MinimumHostingMajorVersionForPersistentVolumeCleanup
            : MinimumHostingMajorVersionForPersistentResourceCleanup;
        var minimumMinorVersion = deleteVolumes
            ? MinimumHostingMinorVersionForPersistentVolumeCleanup
            : MinimumHostingMinorVersionForPersistentResourceCleanup;
 
        if (appHostInfo.IsUsingCliBundle || SupportsCleanup(appHostInfo.AspireHostingVersion, minimumMajorVersion, minimumMinorVersion))
        {
            return;
        }
 
        var appHostVersion = string.IsNullOrWhiteSpace(appHostInfo.AspireHostingVersion)
            ? StopCommandStrings.UnknownAspireHostingVersion
            : appHostInfo.AspireHostingVersion;
        var unsupportedMessage = deleteVolumes
            ? StopCommandStrings.DcpVolumeCleanupUnsupportedAppHostVersion
            : StopCommandStrings.DcpCleanupUnsupportedAppHostVersion;
        var minimumVersionDisplay = deleteVolumes
            ? MinimumHostingVersionForPersistentVolumeCleanupDisplay
            : MinimumHostingVersionForPersistentResourceCleanupDisplay;
        InteractionService.DisplayMessage(KnownEmojis.PoliceCarLight, string.Format(
            CultureInfo.CurrentCulture,
            unsupportedMessage,
            appHostVersion,
            minimumVersionDisplay));
    }
 
    private static bool SupportsCleanup(string? aspireHostingVersion, int minimumMajorVersion, int minimumMinorVersion)
    {
        if (string.IsNullOrWhiteSpace(aspireHostingVersion) ||
            !SemVersion.TryParse(aspireHostingVersion, SemVersionStyles.Any, out var version))
        {
            return false;
        }
 
        return version.Major > minimumMajorVersion ||
            (version.Major == minimumMajorVersion &&
             version.Minor >= minimumMinorVersion);
    }
 
    private bool IsDotNetAppHost(FileInfo appHostFile)
    {
        var language = _languageDiscovery.GetLanguageByFile(appHostFile);
        return language?.LanguageId.Value.Equals(KnownLanguageId.CSharp, StringComparison.OrdinalIgnoreCase) == true;
    }
 
    /// <summary>
    /// Stops all running AppHosts discovered via socket scanning.
    /// </summary>
    private async Task<int> StopAllAppHostsAsync(CancellationToken cancellationToken)
    {
        // First collect AppHosts whose launching CLI has died.
        // Collecting first guarantees orphaned trees and their stale sockets are cleaned up
        // even if the normal stop path can't connect to one of them. CollectAsync is best effort and
        // never throws for scan/stop failures (only cancellation propagates), so no guard is needed here.
        //
        // With --wait, collection is skipped: it only waits for the process to exit, so collected AppHosts
        // could still be removing their resources when the command returns. Orphaned AppHosts are discovered by
        // the same scan below, so they go through the teardown-aware stop and report their cleanup outcome.
        if (!_waitForResourceTeardown)
        {
            var collected = await _collector.CollectAsync(cancellationToken).ConfigureAwait(false);
            if (collected > 0)
            {
                _logger.LogDebug("Collected {Count} orphaned AppHost(s) before stopping the rest.", collected);
 
                // Collection only waits for each process to exit, so these AppHosts' resources may still be stopping.
                Interlocked.Add(ref _appHostsStoppedWithoutTeardownWait, collected);
            }
        }
 
        var allConnections = await _connectionResolver.ResolveAllConnectionsAsync(
            SharedCommandStrings.ScanningForRunningAppHosts,
            cancellationToken);
        _profilingTelemetry.CurrentActivity.SetAppHostStopCount(allConnections.Length);
 
        if (allConnections.Length == 0)
        {
            InteractionService.DisplayMessage(KnownEmojis.Information, SharedCommandStrings.AppHostNotRunning);
            return CliExitCodes.Success;
        }
 
        _logger.LogDebug("Found {Count} running AppHost(s) to stop", allConnections.Length);
 
        var connections = allConnections.Select(connectionResult => connectionResult.Connection!).ToArray();
        var appHostPaths = connections.Select(GetAppHostPath).ToArray();
        var appHostPathComparer = GetAppHostPathComparer();
        var displayPaths = FileSystemHelper.ShortenPaths(appHostPaths, _environment);
        var appHostPathCounts = appHostPaths
            .GroupBy(path => path, appHostPathComparer)
            .ToDictionary(group => group.Key, group => group.Count(), appHostPathComparer);
 
        // Stop all AppHosts in parallel
        var stopTasks = connections.Select(connection =>
        {
            var appHostPath = GetAppHostPath(connection);
            var displayPath = displayPaths[appHostPath];
            var appHostIdentifier = GetAppHostIdentifier(connection, displayPath, appHostPathCounts[appHostPath] > 1);
            _logger.LogDebug("Queuing stop for AppHost: {AppHostPath}", appHostPath);
            return StopAppHostAsync(connection, appHostIdentifier, useConnectionOnly: false, cancellationToken);
        }).ToArray();
 
        var results = await Task.WhenAll(stopTasks);
        var allStopped = results.All(exitCode => exitCode == CliExitCodes.Success);
 
        _logger.LogDebug("Stop all completed. All stopped: {AllStopped}", allStopped);
 
        return allStopped ? CliExitCodes.Success : CliExitCodes.FailedToDotnetRunAppHost;
    }
 
    /// <summary>
    /// Stops a single AppHost, optionally restricting shutdown to its original RPC connection.
    /// </summary>
    private async Task<int> StopAppHostAsync(IAppHostAuxiliaryBackchannel connection, string appHostIdentifier, bool useConnectionOnly, CancellationToken cancellationToken)
    {
        // Stop the selected AppHost
        var appHostPath = connection.AppHostInfo?.AppHostPath ?? "Unknown";
        var appHostInfo = connection.AppHostInfo;
        using var activity = _profilingTelemetry.StartStopAppHost(appHostInfo);
        InteractionService.DisplayMessage(KnownEmojis.Package, string.Format(CultureInfo.CurrentCulture, StopCommandStrings.FoundRunningAppHost, appHostIdentifier));
        _logger.LogDebug("Stopping AppHost: {AppHostPath}", appHostPath);
 
        InteractionService.DisplayMessage(KnownEmojis.StopSign, string.Format(CultureInfo.CurrentCulture, StopCommandStrings.SendingStopSignal, appHostIdentifier));
 
        Func<CancellationToken, Task<bool>> requestRpcStopAsync = connection.StopAppHostAsync;
        var teardown = ResourceTeardownOutcome.NotRequested;
        if (_waitForResourceTeardown)
        {
            teardown = await TearDownResourcesAsync(connection, appHostIdentifier, cancellationToken).ConfigureAwait(false);
            if (teardown is ResourceTeardownOutcome.TornDown or ResourceTeardownOutcome.NotConfirmed or ResourceTeardownOutcome.TimedOut
                or ResourceTeardownOutcome.DeliveryUncertain or ResourceTeardownOutcome.RequestNotSent)
            {
                // The AppHost received the teardown request, or may have, and then stops itself once its resource
                // cleanup is over. It may already have closed the connection, and requesting the stop again over that
                // connection could fail even though the stop is underway, so the RPC stop is skipped. A request that
                // was not sent lost its connection, and another caller's cleanup may be running: a stop request
                // could not be sent either, and must not be, so it is skipped too.
                requestRpcStopAsync = static _ => Task.FromResult(true);
            }
        }
 
        // Concurrent `stop --wait` callers share a single resource cleanup in the AppHost, which keeps running while any
        // of them is still waiting and stops the AppHost only once it is over. After a reply, the AppHost waits briefly
        // before stopping so that the replies to every waiter can still be sent. Signaling or force-killing it in the
        // meantime would close the connection of another caller before that caller received its result, so the
        // process is first only observed:
        // - When this caller's wait timed out, or it cannot tell whether the AppHost received its request (for example,
        //   its connection dropped while the request was in flight), the AppHost may legitimately stay up for another
        //   caller. It is never signaled; if it does not exit, it is left running.
        // - When the request was not sent because this caller's connection was lost first (RequestNotSent), the request
        //   did not start a cleanup, but another caller's request may have, and that caller is still waiting on it.
        //   Only the AppHost can tell, and it can no longer be asked over this connection, so it is treated the same.
        // - When the teardown completed (TornDown or NotConfirmed), the AppHost stops itself shortly after replying. The
        //   regular stop only runs once the observation is over: it finds the AppHost gone and cleans up its launcher,
        //   or escalates for an AppHost that did not exit, by which time every reply has long been sent.
        // A teardown the AppHost rejected (CleanupNotStarted) proves that it has no shared cleanup and so no waiter to
        // interrupt, and the regular stop runs directly.
        var leftForSharedTeardown = teardown is ResourceTeardownOutcome.TimedOut or ResourceTeardownOutcome.DeliveryUncertain or ResourceTeardownOutcome.RequestNotSent;
        var observeFirst = useConnectionOnly
            || (appHostInfo is not null && (leftForSharedTeardown || teardown is ResourceTeardownOutcome.TornDown or ResourceTeardownOutcome.NotConfirmed));
        var stopped = await InteractionService.ShowStatusAsync(
            string.Format(CultureInfo.CurrentCulture, StopCommandStrings.StoppingAppHost, appHostIdentifier),
            async () =>
            {
                if (leftForSharedTeardown && appHostInfo is null)
                {
                    // Without the AppHost's process information its exit cannot be observed, and the regular stop
                    // would only run the skipped RPC stop and report success. The AppHost may still be running for
                    // another caller, so report it as left running.
                    return false;
                }
 
                if (observeFirst)
                {
                    var exited = await _processShutdownService.StopAppHostByConnectionAsync(appHostInfo!, requestRpcStopAsync, cancellationToken).ConfigureAwait(false);
                    if (useConnectionOnly || leftForSharedTeardown)
                    {
                        return exited;
                    }
                }
 
                return await _processShutdownService.StopAppHostAsync(appHostInfo, requestRpcStopAsync, cancellationToken).ConfigureAwait(false);
            });
 
        // Reset cursor position after spinner
        InteractionService.DisplayPlainText("");
 
        if (!stopped && leftForSharedTeardown)
        {
            // The AppHost is still running, so its socket is kept and the stop is reported as failed: --force must not
            // clean up persistent resources under a live AppHost, and --all must not report success.
            DisplayTeardownOutcome(teardown, appHostIdentifier);
            InteractionService.DisplayError(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostLeftRunningDuringResourceTeardown, appHostIdentifier, s_waitOption.Name));
            return CompleteStopActivity(activity, CliExitCodes.FailedToDotnetRunAppHost);
        }
 
        if (!stopped)
        {
            InteractionService.DisplayError(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.FailedToStopAppHost, appHostIdentifier));
            return CompleteStopActivity(activity, CliExitCodes.FailedToDotnetRunAppHost);
        }
 
        // ProcessShutdownService only reports success once it has confirmed the AppHost process has
        // terminated, so the socket's owner is gone and the file is safe to remove by exact path. Doing
        // it here is the primary guard against a stale socket tripping up later commands: the AppHost's own
        // cleanup is skipped if it crashes hard, and the orphan-pruning backstop misfires on Windows when the
        // dead PID is reused (https://github.com/microsoft/aspire/issues/17587).
        connection.Socket.TryDelete();
        InteractionService.DisplaySuccess(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostStoppedSuccessfully, appHostIdentifier));
 
        CompleteStopActivity(activity, DisplayTeardownOutcome(teardown, appHostIdentifier));
 
        // The AppHost itself stopped, so report this stop as successful to the caller. The teardown failure is
        // applied to the command's exit code once every requested step has run.
        return CliExitCodes.Success;
    }
 
    /// <summary>
    /// Asks the AppHost to tear down its resources and waits, up to the <c>--timeout</c> value, for it to
    /// confirm that they are gone.
    /// </summary>
    /// <remarks>
    /// The AppHost process exits before DCP finishes removing its resources, so observing the process alone cannot
    /// tell when containers with fixed names are gone. The AppHost instead asks DCP to clean up its resources and
    /// responds once DCP reports the cleanup complete, then stops itself.
    /// </remarks>
    private async Task<ResourceTeardownOutcome> TearDownResourcesAsync(IAppHostAuxiliaryBackchannel connection, string appHostIdentifier, CancellationToken cancellationToken)
    {
        if (!connection.SupportsStopResourceCleanupV1)
        {
            _logger.LogDebug("AppHost {AppHostIdentifier} does not support waiting for resource teardown.", appHostIdentifier);
            return ResourceTeardownOutcome.Unsupported;
        }
 
        using var timeoutCts = new CancellationTokenSource(_resourceTeardownTimeout, _timeProvider);
        using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCts.Token);
 
        try
        {
            var tornDown = await InteractionService.ShowStatusAsync(
                string.Format(CultureInfo.CurrentCulture, StopCommandStrings.WaitingForResourceTeardown, appHostIdentifier),
                () => connection.StopAppHostAndWaitForResourceCleanupAsync(linkedCts.Token)).ConfigureAwait(false);
 
            // An AppHost that observes the cancellation sent for an expired deadline abandons the cleanup and can
            // still reply that it was not confirmed. That reply is the timeout, not a separate failure.
            return tornDown ? ResourceTeardownOutcome.TornDown
                : timeoutCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested ? ResourceTeardownOutcome.TimedOut
                : ResourceTeardownOutcome.NotConfirmed;
        }
        catch (OperationCanceledException) when (timeoutCts.IsCancellationRequested && !cancellationToken.IsCancellationRequested)
        {
            _logger.LogDebug("Timed out waiting for the resources of AppHost {AppHostIdentifier} to be torn down.", appHostIdentifier);
            return ResourceTeardownOutcome.TimedOut;
        }
        catch (OperationCanceledException ex) when (!cancellationToken.IsCancellationRequested)
        {
            // Neither the command nor its deadline canceled the wait, so the AppHost canceled the request itself.
            // StreamJsonRpc completes a call that the server canceled as canceled, with CancellationToken.None, for
            // example when an AppHost that does not reply with an unconfirmed result shuts down while this caller waits.
            // That is not a failure of the command: report the teardown as unconfirmed, and do not signal an AppHost
            // that may still be running a cleanup shared with other callers.
            _logger.LogDebug(ex, "AppHost {AppHostIdentifier} canceled the request to tear down its resources.", appHostIdentifier);
            return ResourceTeardownOutcome.DeliveryUncertain;
        }
        catch (AppHostRequestNotSentException ex)
        {
            // This request never reached the AppHost, but that does not prove the AppHost has no resource cleanup in
            // progress: another `stop --wait` caller's request may have started one and still be waiting on it.
            _logger.LogDebug(ex, "The request to tear down the resources of AppHost {AppHostIdentifier} was not sent.", appHostIdentifier);
            return ResourceTeardownOutcome.RequestNotSent;
        }
        catch (RemoteMethodNotFoundException ex)
        {
            // The AppHost replied that it does not handle the request, so it cannot be running a resource cleanup shared
            // with other callers, and the regular stop below must still request the stop.
            _logger.LogDebug(ex, "AppHost {AppHostIdentifier} did not start tearing down its resources.", appHostIdentifier);
            return ResourceTeardownOutcome.CleanupNotStarted;
        }
        catch (Exception ex) when (ex is not OperationCanceledException)
        {
            // The AppHost may have received the request and started a resource cleanup shared with other callers, for
            // example when the connection drops while the request is in flight or the cleanup itself fails. StreamJsonRpc
            // reports a connection that was lost before the call with the same ConnectionLostException as one lost
            // after the request was sent, so any failure not proven to precede delivery is treated as uncertain.
            _logger.LogDebug(ex, "Could not confirm that AppHost {AppHostIdentifier} received the request to tear down its resources.", appHostIdentifier);
            return ResourceTeardownOutcome.DeliveryUncertain;
        }
    }
 
    /// <summary>
    /// Reports the outcome of the resource teardown and records any failure for the command's exit code.
    /// </summary>
    private int DisplayTeardownOutcome(ResourceTeardownOutcome teardown, string appHostIdentifier) => teardown switch
    {
        ResourceTeardownOutcome.NotRequested => CountStoppedWithoutTeardownWait(),
        ResourceTeardownOutcome.TornDown => DisplayTeardownSuccess(appHostIdentifier),
        ResourceTeardownOutcome.TimedOut => DisplayTeardownError(CliExitCodes.WaitTimeout, StopCommandStrings.ResourceTeardownTimedOut, appHostIdentifier, (int)_resourceTeardownTimeout.TotalSeconds),
        ResourceTeardownOutcome.Unsupported => DisplayTeardownError(CliExitCodes.AppHostIncompatible, StopCommandStrings.ResourceTeardownUnsupported, appHostIdentifier, s_waitOption.Name),
        _ => DisplayTeardownError(CliExitCodes.FailedToDotnetRunAppHost, StopCommandStrings.ResourceTeardownNotConfirmed, appHostIdentifier)
    };
 
    private int CountStoppedWithoutTeardownWait()
    {
        Interlocked.Increment(ref _appHostsStoppedWithoutTeardownWait);
        return CliExitCodes.Success;
    }
 
    private int DisplayTeardownSuccess(string appHostIdentifier)
    {
        InteractionService.DisplaySuccess(string.Format(CultureInfo.CurrentCulture, StopCommandStrings.ResourcesTornDown, appHostIdentifier));
        return CliExitCodes.Success;
    }
 
    private int DisplayTeardownError(int exitCode, string format, params object[] args)
    {
        InteractionService.DisplayError(string.Format(CultureInfo.CurrentCulture, format, args));
 
        // AppHosts are stopped in parallel (for example with --all), so the command's exit code must not depend on
        // which teardown failure is recorded first. Keep the failure with the highest precedence.
        lock (_resourceTeardownExitCodeLock)
        {
            if (GetTeardownExitCodePrecedence(exitCode) > GetTeardownExitCodePrecedence(_resourceTeardownExitCode))
            {
                _resourceTeardownExitCode = exitCode;
            }
        }
 
        return exitCode;
    }
 
    /// <summary>
    /// Ranks resource teardown failures for the command's exit code: an unconfirmed teardown outranks a timeout, which
    /// outranks an AppHost that does not support waiting. An unconfirmed teardown means the request itself failed
    /// or the AppHost could not confirm the cleanup, which is the most actionable outcome; an unsupported AppHost
    /// is a version limitation that applies regardless of the teardown.
    /// </summary>
    private static int GetTeardownExitCodePrecedence(int exitCode) => exitCode switch
    {
        CliExitCodes.FailedToDotnetRunAppHost => 3,
        CliExitCodes.WaitTimeout => 2,
        CliExitCodes.AppHostIncompatible => 1,
        _ => 0
    };
 
    private static int CompleteStopActivity(ProfilingTelemetry.ActivityScope activity, int exitCode)
    {
        activity.SetProcessExitCode(exitCode);
        if (exitCode != CliExitCodes.Success)
        {
            activity.SetError($"Stop exited with code {exitCode}.");
        }
 
        return exitCode;
    }
 
    private string GetSingleAppHostDisplayPath(IAppHostAuxiliaryBackchannel connection)
    {
        if (string.IsNullOrEmpty(connection.AppHostInfo?.AppHostPath))
        {
            return "Unknown";
        }
 
        var appHostPath = connection.AppHostInfo.AppHostPath;
        return connection.IsInScope
            ? Path.GetRelativePath(ExecutionContext.WorkingDirectory.FullName, appHostPath)
            : appHostPath;
    }
 
    private static string GetAppHostPath(IAppHostAuxiliaryBackchannel connection)
    {
        return string.IsNullOrEmpty(connection.AppHostInfo?.AppHostPath)
            ? "Unknown"
            : connection.AppHostInfo.AppHostPath;
    }
 
    private static FileInfo? GetAppHostFile(IAppHostAuxiliaryBackchannel connection)
    {
        return string.IsNullOrEmpty(connection.AppHostInfo?.AppHostPath)
            ? null
            : new FileInfo(connection.AppHostInfo.AppHostPath);
    }
 
    private static string GetDcpCleanupErrorDetails(DcpWorkloadCleanupResult cleanupResult)
    {
        var details = !string.IsNullOrWhiteSpace(cleanupResult.Error)
            ? cleanupResult.Error
            : cleanupResult.Output;
 
        return string.IsNullOrWhiteSpace(details)
            ? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.DcpCleanupExitCode, cleanupResult.ExitCode)
            : details.Trim();
    }
 
    private StringComparer GetAppHostPathComparer()
    {
        return _environment.IsWindows()
            ? StringComparer.OrdinalIgnoreCase
            : StringComparer.Ordinal;
    }
 
    private static string GetAppHostIdentifier(IAppHostAuxiliaryBackchannel connection, string displayPath, bool includeProcessId)
    {
        return includeProcessId && connection.AppHostInfo is { } appHostInfo
            ? string.Format(CultureInfo.CurrentCulture, StopCommandStrings.AppHostIdentifierWithProcessId, displayPath, appHostInfo.ProcessId)
            : displayPath;
    }
 
    private sealed record StopAppHostResult(int ExitCode, FileInfo? AppHostFile);
 
    private enum ResourceTeardownOutcome
    {
        NotRequested,
        TornDown,
        NotConfirmed,
        TimedOut,
        Unsupported,
 
        /// <summary>The AppHost rejected the request, so it is not running a resource cleanup.</summary>
        CleanupNotStarted,
 
        /// <summary>
        /// The request was not sent because the connection was lost. The AppHost may still be running a resource
        /// cleanup that another caller requested.
        /// </summary>
        RequestNotSent,
 
        /// <summary>The request failed, and the AppHost may have received it and started a resource cleanup.</summary>
        DeliveryUncertain
    }
}